blob: 34981aebb1cbed5f9e541ec0a55adbfd67666182 [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 Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/Layer.h>
45#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070046#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080047#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080049#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080050#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
53
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070055#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080056#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080057#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070060#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <ui/ColorSpace.h>
62#include <ui/DebugUtils.h>
63#include <ui/DisplayInfo.h>
64#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <ui/GraphicBufferAllocator.h>
66#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070067#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/String16.h>
70#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070071#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080072#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070073#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopian921e6ac2012-07-23 23:11:29 -070075#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070076#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Robert Carr578038f2018-03-09 12:25:24 -080078#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070079#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070080#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020083#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070087#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080088#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070089#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070090#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070091#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094
Steven Thomasb02664d2017-07-26 18:48:28 -070095#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070096#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070097#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070098#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070099#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700101#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700103#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/EventControlThread.h"
105#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700106#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700107#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700108#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700109#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800110#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111
Mathias Agopianff2ed702013-09-01 21:36:12 -0700112#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700113
David Sodman7e4ae112018-02-09 15:02:28 -0800114#include "android-base/stringprintf.h"
115
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800117#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
118#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700119#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900120#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
chaviw1d044282017-09-27 12:19:28 -0700122#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
259 mTimeStats(mFactory.createTimeStats()),
260 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700261 mCompositionEngine(mFactory.createCompositionEngine()),
262 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 mDefaultCompositionDataspace =
285 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700286 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
287 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 defaultCompositionDataspace = mDefaultCompositionDataspace;
289 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
290 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
291 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
292 wideColorGamutCompositionPixelFormat =
293 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294
Yichi Chenda901bf2019-06-28 14:58:27 +0800295 mColorSpaceAgnosticDataspace =
296 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
301 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
302 switch (tmpPrimaryDisplayOrientation) {
303 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700304 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800305 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700307 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700310 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
312 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700313 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
315 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700316 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800317
Sundong Ahn85131bd2019-02-18 15:51:53 +0900318 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // debugging stuff...
321 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700322
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700324 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 property_get("debug.sf.showupdates", value, "0");
327 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700329 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000330
331 // DDMS debugging deprecated (b/120782499)
332 property_get("debug.sf.ddms", value, "0");
333 int debugDdms = atoi(value);
334 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700335
336 property_get("debug.sf.disable_backpressure", value, "0");
337 mPropagateBackpressure = !atoi(value);
338 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700339
Ady Abraham4658e112019-07-22 13:07:26 -0700340 property_get("debug.sf.enable_gl_backpressure", value, "0");
341 mPropagateBackpressureClientComposition = atoi(value);
342 ALOGI_IF(mPropagateBackpressureClientComposition,
343 "Enabling backpressure propagation for Client Composition");
344
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800345 property_get("debug.sf.enable_hwc_vds", value, "0");
346 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800347 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800348
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800349 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800350 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800351 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700352
Yiwei Zhang243b3782018-05-15 17:40:04 -0700353 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700354 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
355 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
356
Ana Krulece5a06e02019-03-06 17:09:03 -0800357 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800358 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800359
360 int int_value = atoi(value);
361 if (int_value) {
362 mUseSmart90ForVideo = true;
363 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800364
Dan Stozaec460082018-12-17 15:35:09 -0800365 property_get("debug.sf.luma_sampling", value, "1");
366 mLumaSampling = atoi(value);
367
Romain Guy11d63f42017-07-20 12:47:14 -0700368 // We should be reading 'persist.sys.sf.color_saturation' here
369 // but since /data may be encrypted, we need to wait until after vold
370 // comes online to attempt to read the property. The property is
371 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800372
373 if (useTrebleTestingOverride()) {
374 // Without the override SurfaceFlinger cannot connect to HIDL
375 // services that are not listed in the manifests. Considered
376 // deriving the setting from the set service name, but it
377 // would be brittle if the name that's not 'default' is used
378 // for production purposes later on.
379 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383void SurfaceFlinger::onFirstRef()
384{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800385 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386}
387
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700388SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389
Dan Stozac7014012014-02-14 15:03:43 -0800390void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391{
392 // the window manager died on us. prepare its eulogy.
393
Andy McFadden13a082e2012-08-24 10:16:42 -0700394 // restore initial conditions (default device unblank, etc)
395 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396
397 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399}
400
Robert Carr1db73f62016-12-21 12:58:51 -0800401static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700402 status_t err = client->initCheck();
403 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800404 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 }
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return nullptr;
407}
408
409sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
410 return initClient(new Client(this));
411}
412
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700413sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
414 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415{
416 class DisplayToken : public BBinder {
417 sp<SurfaceFlinger> flinger;
418 virtual ~DisplayToken() {
419 // no more references, this display must be terminated
420 Mutex::Autolock _l(flinger->mStateLock);
421 flinger->mCurrentState.displays.removeItem(this);
422 flinger->setTransactionFlags(eDisplayTransactionNeeded);
423 }
424 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700425 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700426 : flinger(flinger) {
427 }
428 };
429
430 sp<BBinder> token = new DisplayToken(this);
431
432 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700433 // Display ID is assigned when virtual display is allocated by HWC.
434 DisplayDeviceState state;
435 state.isSecure = secure;
436 state.displayName = displayName;
437 mCurrentState.displays.add(token, state);
438 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 return token;
440}
441
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700442void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700443 Mutex::Autolock _l(mStateLock);
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
446 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700447 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700448 return;
449 }
450
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
452 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 ALOGE("destroyDisplay called for non-virtual display");
454 return;
455 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456 mInterceptor->saveDisplayDeletion(state.sequenceId);
457 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 setTransactionFlags(eDisplayTransactionNeeded);
459}
460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800461std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
462 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800464 const auto internalDisplayId = getInternalDisplayIdLocked();
465 if (!internalDisplayId) {
466 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 }
468
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800469 std::vector<PhysicalDisplayId> displayIds;
470 displayIds.reserve(mPhysicalDisplayTokens.size());
471 displayIds.push_back(internalDisplayId->value);
472
473 for (const auto& [id, token] : mPhysicalDisplayTokens) {
474 if (id != *internalDisplayId) {
475 displayIds.push_back(id.value);
476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479 return displayIds;
480}
481
482sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
483 Mutex::Autolock lock(mStateLock);
484 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485}
486
Ady Abraham37965d42018-11-01 13:43:32 -0700487status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
488 if (!outGetColorManagement) {
489 return BAD_VALUE;
490 }
491 *outGetColorManagement = useColorManagement;
492 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700493}
494
Lloyd Pique441d5042018-10-18 16:49:51 -0700495HWComposer& SurfaceFlinger::getHwComposer() const {
496 return mCompositionEngine->getHwComposer();
497}
498
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700499renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
500 return mCompositionEngine->getRenderEngine();
501}
502
Lloyd Pique70d91362018-10-18 16:02:55 -0700503compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
504 return *mCompositionEngine.get();
505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700516 mTimeStats->initializeTracing();
517
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518 // wait patiently for the window manager death
519 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700520 mWindowManager = defaultServiceManager()->getService(name);
521 if (mWindowManager != 0) {
522 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523 }
Robert Carr720e5062018-07-30 17:45:14 -0700524 sp<IBinder> input(defaultServiceManager()->getService(
525 String16("inputflinger")));
526 if (input == nullptr) {
527 ALOGE("Failed to link to input service");
528 } else {
529 mInputFlinger = interface_cast<IInputFlinger>(input);
530 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 if (mVrFlinger) {
533 mVrFlinger->OnBootFinished();
534 }
535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700537 // formerly we would just kill the process, but we now ask it to exit so it
538 // can choose where to stop the animation.
539 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700540
541 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
542 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
543 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700544
Ana Krulecbd6654b2019-02-15 15:18:15 -0800545 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800546 readPersistentProperties();
547 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800548
Ady Abraham97d04232019-03-05 19:48:12 -0800549 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700550 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700551 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800552
Dominik Laskowski22488f62019-03-28 09:53:04 -0700553 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800554 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800556 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800557 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800559}
560
Dan Stoza436ccf32018-06-21 12:10:12 -0700561uint32_t SurfaceFlinger::getNewTexture() {
562 {
563 std::lock_guard lock(mTexturePoolMutex);
564 if (!mTexturePool.empty()) {
565 uint32_t name = mTexturePool.back();
566 mTexturePool.pop_back();
567 ATRACE_INT("TexturePoolSize", mTexturePool.size());
568 return name;
569 }
570
571 // The pool was too small, so increase it for the future
572 ++mTexturePoolSize;
573 }
574
575 // The pool was empty, so we need to get a new texture name directly using a
576 // blocking call to the main thread
577 uint32_t name = 0;
578 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
579 return name;
580}
581
Mathias Agopian3f844832013-08-07 21:24:32 -0700582void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700583 std::lock_guard lock(mTexturePoolMutex);
584 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
585 // to actually delete this or not based on mTexturePoolSize
586 mTexturePool.push_back(texture);
587 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700588}
589
Wei Wangf9b05ee2017-07-19 20:59:39 -0700590// Do not call property_set on main thread which will be blocked by init
591// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700593 ALOGI( "SurfaceFlinger's main thread ready to run. "
594 "Initializing graphics H/W...");
595
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700596 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800600 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700601 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
602 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800603 auto resyncCallback =
604 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800605
Ana Krulecc2870422019-01-29 19:00:58 -0800606 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700607 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700608 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800609 resyncCallback,
610 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700611 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700612 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700613 mPhaseOffsets->getOffsetThresholdForNextVsync(),
614 resyncCallback, [this](nsecs_t timestamp) {
615 mInterceptor->saveVSyncEvent(timestamp);
616 });
Ana Krulecc2870422019-01-29 19:00:58 -0800617
618 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700619
620 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
621 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800622
Kevin DuBois413287f2019-02-25 08:46:47 -0800623 mRegionSamplingThread =
624 new RegionSamplingThread(*this, *mScheduler,
625 RegionSamplingThread::EnvironmentTimingTunables());
626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700628 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700629 renderEngineFeature |= (useColorManagement ?
630 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700631 renderEngineFeature |= (useContextPriority ?
632 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700633 renderEngineFeature |=
634 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
635 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700636
637 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800638 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700639 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700640 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800641 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700642
643 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
644 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700645 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
646 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800647 // Process any initial hotplug and resulting display changes.
648 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700649 const auto display = getDefaultDisplayDeviceLocked();
650 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700651 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800653
Steven Thomas050b2c82017-03-06 11:45:16 -0800654 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700656 // This callback is called from the vr flinger dispatch thread. We
657 // need to call signalTransaction(), which requires holding
658 // mStateLock when we're not on the main thread. Acquiring
659 // mStateLock from the vr flinger dispatch thread might trigger a
660 // deadlock in surface flinger (see b/66916578), so post a message
661 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700662 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700663 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
664 mVrFlingerRequestsDisplay = requestDisplay;
665 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700668 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
669 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700670 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 .value_or(0),
672 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 if (!mVrFlinger) {
674 ALOGE("Failed to start vrflinger");
675 }
676 }
677
Mathias Agopian92a979a2012-08-02 18:32:23 -0700678 // initialize our drawing state
679 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700680
Andy McFadden13a082e2012-08-24 10:16:42 -0700681 // set initial conditions (e.g. unblank default device)
682 initializeDisplays();
683
Steven Thomas137d4bc2019-07-25 16:55:14 -0700684 char primeShaderCache[PROPERTY_VALUE_MAX];
685 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
686 if (atoi(primeShaderCache)) {
687 getRenderEngine().primeCache();
688 }
Dan Stoza4e637772016-07-28 13:31:51 -0700689
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700691
692 const bool presentFenceReliable =
693 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
694 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695
696 if (mStartPropertySetThread->Start() != NO_ERROR) {
697 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699
Alec Mouri93bc83d2019-04-17 14:47:43 -0700700 mScheduler->setChangeRefreshRateCallback(
701 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
702 Mutex::Autolock lock(mStateLock);
703 setRefreshRateTo(type, event);
704 });
Alec Mouri7f015182019-07-11 13:56:22 -0700705 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
706 Mutex::Autolock lock(mStateLock);
707 const auto display = getDefaultDisplayDeviceLocked();
708 if (!display) {
709 // If we don't have a default display the fallback to the default
710 // refresh rate type
711 return RefreshRateType::DEFAULT;
712 }
713
714 const int configId = display->getActiveConfig();
715 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
716 if (refresh && refresh->configId == configId) {
717 return type;
718 }
719 }
720 // This should never happen, but just gracefully fallback to default.
721 return RefreshRateType::DEFAULT;
722 });
Alec Mouridc28b372019-04-18 21:17:13 -0700723 mScheduler->setGetVsyncPeriodCallback([this] {
724 Mutex::Autolock lock(mStateLock);
725 return getVsyncPeriod();
726 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700727
Dominik Laskowski22488f62019-03-28 09:53:04 -0700728 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
729 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700732}
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700735 Mutex::Autolock _l(mStateLock);
736
Romain Guy11d63f42017-07-20 12:47:14 -0700737 char value[PROPERTY_VALUE_MAX];
738
739 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100743
744 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700745 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800746
747 property_get("persist.sys.sf.color_mode", value, "0");
748 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700749}
750
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800752 // Start boot animation service by setting a property mailbox
753 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756 if (mStartPropertySetThread->join() != NO_ERROR) {
757 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800758 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700762 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800770
Jamie Gennis582270d2011-08-17 18:19:00 -0700771bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800772 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800773 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800774 return authenticateSurfaceTextureLocked(bufferProducer);
775}
776
777bool SurfaceFlinger::authenticateSurfaceTextureLocked(
778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800779 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800780 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800781}
782
Brian Anderson6b376712017-04-04 10:51:39 -0700783status_t SurfaceFlinger::getSupportedFrameTimestamps(
784 std::vector<FrameEvent>* outSupported) const {
785 *outSupported = {
786 FrameEvent::REQUESTED_PRESENT,
787 FrameEvent::ACQUIRE,
788 FrameEvent::LATCH,
789 FrameEvent::FIRST_REFRESH_START,
790 FrameEvent::LAST_REFRESH_START,
791 FrameEvent::GPU_COMPOSITION_DONE,
792 FrameEvent::DEQUEUE_READY,
793 FrameEvent::RELEASE,
794 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 ConditionalLock _l(mStateLock,
796 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700797 if (!getHwComposer().hasCapability(
798 HWC2::Capability::PresentFenceIsNotReliable)) {
799 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
800 }
801 return NO_ERROR;
802}
803
Dominik Laskowski22488f62019-03-28 09:53:04 -0700804status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
805 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700806 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 return BAD_VALUE;
808 }
809
Dominik Laskowski22488f62019-03-28 09:53:04 -0700810 Mutex::Autolock lock(mStateLock);
811
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800812 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 if (!displayId) {
814 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700815 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 // TODO: Not sure if display density should handled by SF any longer
818 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700819 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700821 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800822 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 }
825 return density;
826 }
827 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("ro.sf.lcd_density"); }
832 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dominik Laskowski075d3172018-05-24 15:50:06 -0700836 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 DisplayInfo info = DisplayInfo();
838
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 float xdpi = hwConfig->getDpiX();
840 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700842 info.w = hwConfig->getWidth();
843 info.h = hwConfig->getHeight();
844 // Default display viewport to display width and height
845 info.viewportW = info.w;
846 info.viewportH = info.h;
847
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800848 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 // The density of the device is provided by a build property
850 float density = Density::getBuildDensity() / 160.0f;
851 if (density == 0) {
852 // the build doesn't provide a density -- this is wrong!
853 // use xdpi instead
854 ALOGE("ro.sf.lcd_density must be defined as a build property");
855 density = xdpi / 160.0f;
856 }
857 if (Density::getEmuDensity()) {
858 // if "qemu.sf.lcd_density" is specified, it overrides everything
859 xdpi = ydpi = density = Density::getEmuDensity();
860 density /= 160.0f;
861 }
862 info.density = density;
863
864 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700865 const auto display = getDefaultDisplayDeviceLocked();
866 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700867
868 // This is for screenrecord
869 const Rect viewport = display->getViewport();
870 if (viewport.isValid()) {
871 info.viewportW = uint32_t(viewport.getWidth());
872 info.viewportH = uint32_t(viewport.getHeight());
873 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 } else {
875 // TODO: where should this value come from?
876 static const int TV_DENSITY = 213;
877 info.density = TV_DENSITY / 160.0f;
878 info.orientation = 0;
879 }
880
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 info.xdpi = xdpi;
882 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700884 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
885 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
886 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887
Andy McFadden91b2ca82014-06-13 14:04:23 -0700888 // This is how far in advance a buffer must be queued for
889 // presentation at a given time. If you want a buffer to appear
890 // on the screen at time N, you must submit the buffer before
891 // (N - presentationDeadline).
892 //
893 // Normally it's one full refresh period (to give SF a chance to
894 // latch the buffer), but this can be reduced by configuring a
895 // DispSync offset. Any additional delays introduced by the hardware
896 // composer or panel must be accounted for here.
897 //
898 // We add an additional 1ms to allow for processing time and
899 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700900 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
902 // All non-virtual displays are currently considered secure.
903 info.secure = true;
904
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800905 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700906 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800907 std::swap(info.w, info.h);
908 }
909
Michael Wright28f24d02016-07-12 13:30:53 -0700910 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulecc2870422019-01-29 19:00:58 -0800921 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Ady Abraham03b02dd2019-03-21 15:40:11 -0700935void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800937
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800939 // config twice. However event generation config might have changed so we need to update it
940 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800941 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700942 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
943 mDesiredActiveConfig = info;
944 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945
946 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800947 // This will trigger HWC refresh without resetting the idle timer.
948 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700949 // Start receiving vsync samples now, so that we can detect a period
950 // switch.
951 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700952 // As we called to set period, we will call to onRefreshRateChangeCompleted once
953 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700954 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700955 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700956 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800957 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700959
960 if (mRefreshRateOverlay) {
961 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
962 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963}
964
965status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
966 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800967
968 std::vector<int32_t> allowedConfig;
969 allowedConfig.push_back(mode);
970
971 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972}
973
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974void SurfaceFlinger::setActiveConfigInternal() {
975 ATRACE_CALL();
976
Dominik Laskowski22488f62019-03-28 09:53:04 -0700977 const auto display = getDefaultDisplayDeviceLocked();
978 if (!display) {
979 return;
980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981
Dominik Laskowski22488f62019-03-28 09:53:04 -0700982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
983 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
984
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 display->setActiveConfig(mUpcomingActiveConfig.configId);
986
Alec Mouri754c98a2019-03-18 18:53:42 -0700987 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700988 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700990
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800991 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800992 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
993 mUpcomingActiveConfig.configId);
994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995}
996
Ady Abraham53852a52019-05-28 18:07:44 -0700997void SurfaceFlinger::desiredActiveConfigChangeDone() {
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1000 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001001
1002 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1003 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001004 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001005}
1006
Dominik Laskowski22488f62019-03-28 09:53:04 -07001007bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001008 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001010 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001012 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 return true;
1014 }
1015
1016 // We received the present fence from the HWC, so we assume it successfully updated
1017 // the config, hence we update SF.
1018 mCheckPendingFence = false;
1019 setActiveConfigInternal();
1020 }
1021
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 // Store the local variable to release the lock.
1023 ActiveConfigInfo desiredActiveConfig;
1024 {
1025 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (!mDesiredActiveConfigChanged) {
1027 return false;
1028 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 desiredActiveConfig = mDesiredActiveConfig;
1030 }
1031
Dominik Laskowski22488f62019-03-28 09:53:04 -07001032 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1034 // display is not valid or we are already in the requested mode
1035 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001036 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001038 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039
Ady Abraham838de062019-02-04 10:24:03 -08001040 // Desired active config was set, it is different than the config currently in use, however
1041 // allowed configs might have change by the time we process the refresh.
1042 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001043 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001044 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001045 return false;
1046 }
Alec Mouri7f015182019-07-11 13:56:22 -07001047
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 mUpcomingActiveConfig = desiredActiveConfig;
1049 const auto displayId = display->getId();
1050 LOG_ALWAYS_FATAL_IF(!displayId);
1051
1052 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1053 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1054
1055 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001057 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001059}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001060
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1062 Vector<ColorMode>* outColorModes) {
1063 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 return BAD_VALUE;
1065 }
1066
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001068 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001070 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1071
1072 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1073 if (!displayId) {
1074 return NAME_NOT_FOUND;
1075 }
1076
Dominik Laskowski075d3172018-05-24 15:50:06 -07001077 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001078 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001081
1082 // If it's built-in display and the configuration claims it's not wide color capable,
1083 // filter out all wide color modes. The typical reason why this happens is that the
1084 // hardware is not good enough to support GPU composition of wide color, and thus the
1085 // OEMs choose to disable this capability.
1086 if (isInternalDisplay && !hasWideColorDisplay) {
1087 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1088 isWideColorMode);
1089 } else {
1090 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1091 }
Michael Wright28f24d02016-07-12 13:30:53 -07001092
1093 return NO_ERROR;
1094}
1095
Daniel Solomon42d04562019-01-20 21:03:19 -08001096status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1097 ui::DisplayPrimaries &primaries) {
1098 if (!displayToken) {
1099 return BAD_VALUE;
1100 }
1101
1102 // Currently we only support this API for a single internal display.
1103 if (getInternalDisplayToken() != displayToken) {
1104 return BAD_VALUE;
1105 }
1106
1107 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1108 return NO_ERROR;
1109}
1110
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1112 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001113 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001115 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001119 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 Vector<ColorMode> modes;
1121 getDisplayColorModes(displayToken, &modes);
1122 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1123 if (mode < ColorMode::NATIVE || !exists) {
1124 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDevice(displayToken);
1129 if (!display) {
1130 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 } else if (display->isVirtual()) {
1133 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1134 decodeColorMode(mode).c_str(), mode);
1135 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001136 display->getCompositionDisplay()->setColorProfile(
1137 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1138 RenderIntent::COLORIMETRIC,
1139 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001140 }
1141 }));
1142
Michael Wright28f24d02016-07-12 13:30:53 -07001143 return NO_ERROR;
1144}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001145
Svetoslavd85084b2014-03-20 10:28:31 -07001146status_t SurfaceFlinger::clearAnimationFrameStats() {
1147 Mutex::Autolock _l(mStateLock);
1148 mAnimFrameTracker.clearStats();
1149 return NO_ERROR;
1150}
1151
1152status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1153 Mutex::Autolock _l(mStateLock);
1154 mAnimFrameTracker.getStats(outStats);
1155 return NO_ERROR;
1156}
1157
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1159 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001160 Mutex::Autolock _l(mStateLock);
1161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001162 const auto display = getDisplayDeviceLocked(displayToken);
1163 if (!display) {
1164 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001165 return BAD_VALUE;
1166 }
1167
Peiyong Linfb069302018-04-25 14:34:31 -07001168 // At this point the DisplayDeivce should already be set up,
1169 // meaning the luminance information is already queried from
1170 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001172 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1173 capabilities.getDesiredMaxLuminance(),
1174 capabilities.getDesiredMaxAverageLuminance(),
1175 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001176
1177 return NO_ERROR;
1178}
1179
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001180status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1181 ui::PixelFormat* outFormat,
1182 ui::Dataspace* outDataspace,
1183 uint8_t* outComponentMask) const {
1184 if (!outFormat || !outDataspace || !outComponentMask) {
1185 return BAD_VALUE;
1186 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001187 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001188 if (!display || !display->getId()) {
1189 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1190 return BAD_VALUE;
1191 }
1192 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1193 outDataspace, outComponentMask);
1194}
1195
Kevin DuBois74e53772018-11-19 10:52:38 -08001196status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1197 bool enable, uint8_t componentMask,
1198 uint64_t maxFrames) const {
1199 const auto display = getDisplayDevice(displayToken);
1200 if (!display || !display->getId()) {
1201 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1202 return BAD_VALUE;
1203 }
1204
1205 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1206 componentMask, maxFrames);
1207}
1208
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001209status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1210 uint64_t maxFrames, uint64_t timestamp,
1211 DisplayedFrameStats* outStats) const {
1212 const auto display = getDisplayDevice(displayToken);
1213 if (!display || !display->getId()) {
1214 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1215 return BAD_VALUE;
1216 }
1217
1218 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1219 outStats);
1220}
1221
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001222status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1223 if (!outSupported) {
1224 return BAD_VALUE;
1225 }
1226 *outSupported = getRenderEngine().supportsProtectedContent();
1227 return NO_ERROR;
1228}
1229
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001230status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1231 bool* outIsWideColorDisplay) const {
1232 if (!displayToken || !outIsWideColorDisplay) {
1233 return BAD_VALUE;
1234 }
1235 Mutex::Autolock _l(mStateLock);
1236 const auto display = getDisplayDeviceLocked(displayToken);
1237 if (!display) {
1238 return BAD_VALUE;
1239 }
Peiyong Linff84a152019-05-17 18:36:19 -07001240
1241 // Use hasWideColorDisplay to override built-in display.
1242 const auto displayId = display->getId();
1243 if (displayId && displayId == getInternalDisplayIdLocked()) {
1244 *outIsWideColorDisplay = hasWideColorDisplay;
1245 return NO_ERROR;
1246 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001247 *outIsWideColorDisplay = display->hasWideColorGamut();
1248 return NO_ERROR;
1249}
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001252 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 if (mInjectVSyncs == enable) {
1256 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258
Ana Krulecc2870422019-01-29 19:00:58 -08001259 auto resyncCallback =
1260 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001262 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001263 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001264 if (enable) {
1265 ALOGV("VSync Injections enabled");
1266 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001267 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001269 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001270 impl::EventThread::InterceptVSyncsCallback(),
1271 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001273 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 } else {
1275 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001276 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1277 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001278 }
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001281 }));
1282
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001283 return NO_ERROR;
1284}
1285
1286status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001287 Mutex::Autolock _l(mStateLock);
1288
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001289 if (!mInjectVSyncs) {
1290 ALOGE("VSync Injections not enabled");
1291 return BAD_VALUE;
1292 }
1293 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1294 ALOGV("Injecting VSync inside SurfaceFlinger");
1295 mVSyncInjector->onInjectSyncEvent(when);
1296 }
1297 return NO_ERROR;
1298}
1299
Lloyd Pique755e3192018-01-31 16:46:15 -08001300status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1301 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001302 // Try to acquire a lock for 1s, fail gracefully
1303 const status_t err = mStateLock.timedLock(s2ns(1));
1304 const bool locked = (err == NO_ERROR);
1305 if (!locked) {
1306 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1307 return TIMED_OUT;
1308 }
1309
1310 outLayers->clear();
1311 mCurrentState.traverseInZOrder([&](Layer* layer) {
1312 outLayers->push_back(layer->getLayerDebugInfo());
1313 });
1314
1315 mStateLock.unlock();
1316 return NO_ERROR;
1317}
1318
Peiyong Linc6780972018-10-28 15:24:08 -07001319status_t SurfaceFlinger::getCompositionPreference(
1320 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1321 Dataspace* outWideColorGamutDataspace,
1322 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001325 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001326 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001327 return NO_ERROR;
1328}
1329
Dan Stozaec460082018-12-17 15:35:09 -08001330status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1331 const sp<IBinder>& stopLayerHandle,
1332 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001333 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001334 return BAD_VALUE;
1335 }
1336 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001337 return NO_ERROR;
1338}
1339
Dan Stozaec460082018-12-17 15:35:09 -08001340status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001341 if (!listener) {
1342 return BAD_VALUE;
1343 }
Dan Stozaec460082018-12-17 15:35:09 -08001344 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001345 return NO_ERROR;
1346}
Dan Gittik57e63c52019-01-18 16:37:54 +00001347
1348status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1349 bool* outSupport) const {
1350 if (!displayToken || !outSupport) {
1351 return BAD_VALUE;
1352 }
1353 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1354 if (!displayId) {
1355 return NAME_NOT_FOUND;
1356 }
1357 *outSupport =
1358 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1359 return NO_ERROR;
1360}
1361
1362status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1363 float brightness) const {
1364 if (!displayToken) {
1365 return BAD_VALUE;
1366 }
1367 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1368 if (!displayId) {
1369 return NAME_NOT_FOUND;
1370 }
1371 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1372}
1373
Ady Abraham8532d012019-05-08 14:50:56 -07001374status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1375 PowerHint powerHint = static_cast<PowerHint>(hintId);
1376
1377 if (powerHint == PowerHint::INTERACTION) {
1378 mScheduler->notifyTouchEvent();
1379 }
1380
1381 return NO_ERROR;
1382}
1383
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001384// ----------------------------------------------------------------------------
1385
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001386sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001387 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001388 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389 Mutex::Autolock lock(mStateLock);
1390 return getVsyncPeriod();
1391 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001392
Ana Krulecc2870422019-01-29 19:00:58 -08001393 const auto& handle =
1394 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001395
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001396 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1397 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001398}
1399
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001400// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001401
1402void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001403 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001404}
1405
1406void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001407 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001408 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001409}
1410
1411void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001412 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001413 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001414}
1415
1416void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001417 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001418 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001419}
1420
1421status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001422 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001423 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424}
1425
1426status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001427 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001428 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001429 if (res == NO_ERROR) {
1430 msg->wait();
1431 }
1432 return res;
1433}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001434
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001435void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001436 do {
1437 waitForEvent();
1438 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001439}
1440
Dominik Laskowski83b88212018-12-11 13:34:06 -08001441nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001442 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001443 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1444 return 0;
1445 }
1446
1447 const auto config = getHwComposer().getActiveConfig(*displayId);
1448 return config ? config->getVsyncPeriod() : 0;
1449}
1450
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001451void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1452 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001453 ATRACE_NAME("SF onVsync");
1454
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001457 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 return;
1459 }
1460
Dominik Laskowski075d3172018-05-24 15:50:06 -07001461 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001462 return;
1463 }
1464
Dominik Laskowski075d3172018-05-24 15:50:06 -07001465 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001466 // For now, we don't do anything with external display vsyncs.
1467 return;
1468 }
1469
Alec Mourif8e689c2019-05-20 18:32:22 -07001470 bool periodFlushed = false;
1471 mScheduler->addResyncSample(timestamp, &periodFlushed);
1472 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001473 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001474 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001475}
1476
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001477void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001478 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1479 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480}
1481
Ady Abraham261614e2019-07-10 17:53:12 -07001482bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001483 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001484}
1485
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001486void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001487 const auto display = getDefaultDisplayDeviceLocked();
1488 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001489 return;
1490 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001491 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001492
Ana Krulec7d1d6832018-12-27 11:10:09 -08001493 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001494 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001495 if (!refreshRateConfig) {
1496 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001497 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001498 }
Ady Abraham1902d072019-03-01 17:18:59 -08001499
Alec Mouri0a1cc962019-03-14 12:33:02 -07001500 const int desiredConfigId = refreshRateConfig->configId;
1501
Dominik Laskowski22488f62019-03-28 09:53:04 -07001502 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001503 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1504 return;
1505 }
1506
Dominik Laskowski22488f62019-03-28 09:53:04 -07001507 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508}
1509
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001510void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001511 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001512 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001513 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001514
Lloyd Piqueba04e622017-12-14 17:11:26 -08001515 // Ignore events that do not have the right sequenceId.
1516 if (sequenceId != getBE().mComposerSequenceId) {
1517 return;
1518 }
1519
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 // Only lock if we're not on the main thread. This function is normally
1521 // called on a hwbinder thread, but for the primary display it's called on
1522 // the main thread with the state lock already held, so don't attempt to
1523 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001524 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001525
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001526 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001527
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001528 if (std::this_thread::get_id() == mMainThreadId) {
1529 // Process all pending hot plug events immediately if we are on the main thread.
1530 processDisplayHotplugEventsLocked();
1531 }
1532
Lloyd Piqueba04e622017-12-14 17:11:26 -08001533 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001534}
1535
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001536void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001537 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001538 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001540 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001541 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001542}
1543
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001544void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001545 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001546
1547 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1548 // display power state.
1549 postMessageAsync(new LambdaMessage(
1550 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1551}
1552
1553void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1554 ATRACE_CALL();
1555
Ady Abraham27c70212019-06-11 10:52:26 -07001556 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1557
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001558 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001559 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1560 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001561 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001562 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001563 }
Mathias Agopian86303202012-07-24 22:46:10 -07001564}
1565
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001566// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001567void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001568 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569 // Clear the drawing state so that the logic inside of
1570 // handleTransactionLocked will fire. It will determine the delta between
1571 // mCurrentState and mDrawingState and re-apply all changes when we make the
1572 // transition.
1573 mDrawingState.displays.clear();
1574 mDisplays.clear();
1575}
1576
Steven Thomas050b2c82017-03-06 11:45:16 -08001577void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001578 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001579 if (!mVrFlinger)
1580 return;
1581 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001582 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001583 return;
1584 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 ALOGE("Vr flinger is only supported for remote hardware composer"
1588 " service connections. Ignoring request to transition to vr"
1589 " flinger.");
1590 mVrFlingerRequestsDisplay = false;
1591 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001592 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001595
Steven Thomas0123ac62018-07-12 11:32:34 -07001596 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001597 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001598
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001599 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001600
1601 // Clear out all the output layers from the composition engine for all
1602 // displays before destroying the hardware composer interface. This ensures
1603 // any HWC layers are destroyed through that interface before it becomes
1604 // invalid.
1605 for (const auto& [token, displayDevice] : mDisplays) {
1606 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1607 compositionengine::Output::OutputLayers());
1608 }
1609
Steven Thomas0123ac62018-07-12 11:32:34 -07001610 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1611 // called below. Clear the reference now so we don't accidentally use it
1612 // later.
1613 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001616 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001617 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001618
Steven Thomasb02664d2017-07-26 18:48:28 -07001619 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001620 // Delete the current instance before creating the new one
1621 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1622 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1623 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1624 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001625
Lloyd Pique441d5042018-10-18 16:49:51 -07001626 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001627 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001628
1629 if (vrFlingerRequestsDisplay) {
1630 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001631 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001632
1633 mVisibleRegionsDirty = true;
1634 invalidateHwcGeometry();
1635
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001636 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001637 display = getDefaultDisplayDeviceLocked();
1638 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001639 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001640
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001642 const nsecs_t vsyncPeriod = getVsyncPeriod();
1643 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001644
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001645 // The present fences returned from vr_hwc are not an accurate
1646 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001647 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001648
Steven Thomasb02664d2017-07-26 18:48:28 -07001649 // Use phase of 0 since phase is not known.
1650 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001651 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001652 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001653
Ana Krulecc2870422019-01-29 19:00:58 -08001654 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001655
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001656 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001657 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001658}
1659
Ady Abrahambe0f9482019-04-24 15:41:53 -07001660bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1661 // We are storing the last 2 present fences. If sf's phase offset is to be
1662 // woken up before the actual vsync but targeting the next vsync, we need to check
1663 // fence N-2
1664 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001665 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001666 ? mPreviousPresentFences[0]
1667 : mPreviousPresentFences[1];
1668
1669 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1670}
1671
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001672void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001673 DisplayStatInfo stats;
1674 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001675 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001676 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001677 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001678 mPhaseOffsets->getOffsetThresholdForNextVsync()
1679 ? presentTime
1680 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001681}
1682
Dominik Laskowski22488f62019-03-28 09:53:04 -07001683void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001684 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001685 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001686 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001687 // calculate the expected present time once and use the cached
1688 // value throughout this frame to make sure all layers are
1689 // seeing this same value.
1690 populateExpectedPresentTime();
1691
Ady Abraham50204dd2019-07-19 15:47:11 -07001692 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1693 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1694 mHadDeviceComposition && frameMissed};
1695 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1696 mHadClientComposition && frameMissed};
1697
Alec Mouricc0fc602019-02-26 21:45:19 -08001698 if (frameMissed) {
1699 mFrameMissedCount++;
1700 mTimeStats->incrementMissedFrames();
1701 }
1702
Alec Mouri40189b02019-03-05 15:07:54 -08001703 if (hwcFrameMissed) {
1704 mHwcFrameMissedCount++;
1705 }
1706
1707 if (gpuFrameMissed) {
1708 mGpuFrameMissedCount++;
1709 }
1710
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001711 if (mUseSmart90ForVideo) {
1712 // This call is made each time SF wakes up and creates a new frame. It is part
1713 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001714 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001715 }
1716
Ady Abrahamb838aed2019-02-12 15:30:16 -08001717 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001718 break;
1719 }
1720
Ady Abraham4658e112019-07-22 13:07:26 -07001721 if (frameMissed && mPropagateBackpressure) {
1722 if ((hwcFrameMissed && !gpuFrameMissed) ||
1723 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001724 signalLayerUpdate();
1725 break;
1726 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001727 }
Dan Stoza50182882016-07-08 12:02:20 -07001728
Steven Thomas050b2c82017-03-06 11:45:16 -08001729 // Now that we're going to make it to the handleMessageTransaction()
1730 // call below it's safe to call updateVrFlinger(), which will
1731 // potentially trigger a display handoff.
1732 updateVrFlinger();
1733
Dan Stoza6b9454d2014-11-07 16:00:59 -08001734 bool refreshNeeded = handleMessageTransaction();
1735 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001736
1737 updateCursorAsync();
1738 updateInputFlinger();
1739
Dan Stoza58784442014-12-02 16:58:17 -08001740 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001741 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001742 // Signal a refresh if a transaction modified the window state,
1743 // a new buffer was latched, or if HWC has requested a full
1744 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001745 signalRefresh();
1746 }
1747 break;
1748 }
1749 case MessageQueue::REFRESH: {
1750 handleMessageRefresh();
1751 break;
1752 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001753 }
1754}
1755
Dan Stoza6b9454d2014-11-07 16:00:59 -08001756bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001757 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001758 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001759
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001760 bool flushedATransaction = flushTransactionQueues();
1761
1762 bool runHandleTransaction = transactionFlags &&
1763 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1764
1765 if (runHandleTransaction) {
1766 handleTransaction(eTransactionMask);
1767 } else {
1768 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001769 }
1770
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001771 if (transactionFlushNeeded()) {
1772 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001774
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001775 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001776}
1777
Mathias Agopian4fec8732012-06-29 14:12:52 -07001778void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001779 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001780
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001781 mRefreshPending = false;
1782
Lloyd Piqueab039b52019-02-13 14:22:42 -08001783 compositionengine::CompositionRefreshArgs refreshArgs;
1784 for (const auto& [_, display] : mDisplays) {
1785 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1786 }
1787 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1788 auto compositionLayer = layer->getCompositionLayer();
1789 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1790 });
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001791 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001792 refreshArgs.outputColorSetting = useColorManagement
1793 ? mDisplayColorSetting
1794 : compositionengine::OutputColorSetting::kUnmanaged;
1795 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1796 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001797 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid;
1798
1799 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1800 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1801 mDrawingState.colorMatrixChanged = false;
1802 }
1803
1804 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1805
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001806 if (mDebugRegion != 0) {
1807 refreshArgs.devOptFlashDirtyRegionsDelay =
1808 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1809 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001810
Lloyd Piqueab039b52019-02-13 14:22:42 -08001811 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001812 rebuildLayerStacks();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001813 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid; // Can be set by rebuildLayerStacks()
Lloyd Piqued7b429f2019-03-07 21:11:02 -08001814 mCompositionEngine->present(refreshArgs);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001815
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001816 mGeometryInvalid = false;
1817
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001819 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001820
Lloyd Pique66d68602019-02-13 14:23:31 -08001821 mHadClientComposition =
1822 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1823 auto& displayDevice = tokenDisplayPair.second;
1824 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1825 });
1826 mHadDeviceComposition =
1827 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1828 auto& displayDevice = tokenDisplayPair.second;
1829 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1830 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001831
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001832 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001833
David Sodman7e4ae112018-02-09 15:02:28 -08001834 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001835 if (mVisibleRegionsDirty) {
1836 mVisibleRegionsDirty = false;
1837 if (mTracingEnabled) {
1838 mTracing.notify("visibleRegionsDirty");
1839 }
1840 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001841
1842 if (mCompositionEngine->needsAnotherUpdate()) {
1843 signalLayerUpdate();
1844 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001846
David Sodmanfa9b2af2017-12-24 13:28:59 -08001847
1848bool SurfaceFlinger::handleMessageInvalidate() {
1849 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001850 bool refreshNeeded = handlePageFlip();
1851
Vishnu Nair4351ad52019-02-11 14:13:02 -08001852 if (mVisibleRegionsDirty) {
1853 computeLayerBounds();
1854 }
1855
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001856 for (auto& layer : mLayersPendingRefresh) {
1857 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001858 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001859 invalidateLayerStack(layer, visibleReg);
1860 }
1861 mLayersPendingRefresh.clear();
1862 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001863}
1864
Ana Krulece588e312018-09-18 12:32:24 -07001865void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1866 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001867 // Update queue of past composite+present times and determine the
1868 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001869 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001870 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001871 while (!getBE().mCompositePresentTimes.empty()) {
1872 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001873 // Cached values should have been updated before calling this method,
1874 // which helps avoid duplicate syscalls.
1875 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1876 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1877 break;
1878 }
1879 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001880 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001881 }
1882
1883 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001884 while (getBE().mCompositePresentTimes.size() > 16) {
1885 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001886 }
1887
Ana Krulece588e312018-09-18 12:32:24 -07001888 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001889}
1890
Ana Krulece588e312018-09-18 12:32:24 -07001891void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1892 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001893 // Integer division and modulo round toward 0 not -inf, so we need to
1894 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001895 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1896 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1897 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898
Ana Krulec757f63a2019-01-25 10:46:18 -08001899 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001900 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001901 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001902 }
1903
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 // Snap the latency to a value that removes scheduling jitter from the
1905 // composition and present times, which often have >1ms of jitter.
1906 // Reducing jitter is important if an app attempts to extrapolate
1907 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001908 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001910 nsecs_t bias = stats.vsyncPeriod / 2;
1911 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1912 nsecs_t snappedCompositeToPresentLatency =
1913 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914
David Sodman99974d22017-11-28 12:04:33 -08001915 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001916 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1917 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001918 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919}
1920
David Sodman2b406362017-12-15 13:33:47 -08001921void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001922{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 ATRACE_CALL();
1924 ALOGV("postComposition");
1925
Brian Anderson3546a3f2016-07-14 11:51:14 -07001926 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001927 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001928 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001929 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001930 }
1931
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001932 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001933 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001934
David Sodman73beded2017-11-15 11:56:06 -08001935 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001936 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001937 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001938 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001939 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1940 ->getRenderSurface()
1941 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001942 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001943 } else {
1944 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1945 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001946
David Sodman73beded2017-11-15 11:56:06 -08001947 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001948 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1949 mPreviousPresentFences[0] = displayDevice
1950 ? getHwComposer().getPresentFence(*displayDevice->getId())
1951 : Fence::NO_FENCE;
1952 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001953 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001954
Ana Krulece588e312018-09-18 12:32:24 -07001955 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001956 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957
Lloyd Piqueab039b52019-02-13 14:22:42 -08001958 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1959 // be sampled a little later than when we started doing work for this frame,
1960 // but that should be okay since updateCompositorTiming has snapping logic.
1961 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1962 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001963 CompositorTiming compositorTiming;
1964 {
David Sodman99974d22017-11-28 12:04:33 -08001965 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1966 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001967 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968
Robert Carr2047fae2016-11-28 14:09:09 -08001969 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001970 bool frameLatched =
1971 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1972 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001973 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001974 recordBufferingStats(layer->getName().string(),
1975 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001976 }
Robert Carr2047fae2016-11-28 14:09:09 -08001977 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001978
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001979 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001980 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001981 }
1982
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001983 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1985 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001986 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001987 }
1988 }
1989
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001990 if (mAnimCompositionPending) {
1991 mAnimCompositionPending = false;
1992
Brian Anderson4e606e32017-03-16 15:34:57 -07001993 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001994 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001995 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001996 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001997 // The HWC doesn't support present fences, so use the refresh
1998 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001999 const nsecs_t presentTime =
2000 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002001 mAnimFrameTracker.setActualPresentTime(presentTime);
2002 }
2003 mAnimFrameTracker.advanceFrame();
2004 }
Dan Stozab90cf072015-03-05 11:05:59 -08002005
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002006 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002007 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002008 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002009 }
2010
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002011 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002012
Lloyd Pique32cbe282018-10-19 13:09:22 -07002013 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2014 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002015 return;
2016 }
2017
2018 nsecs_t currentTime = systemTime();
2019 if (mHasPoweredOff) {
2020 mHasPoweredOff = false;
2021 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002022 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002023 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002024 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2025 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002026 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002027 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002028 }
David Sodman4a36e932017-11-07 14:29:47 -08002029 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002030 }
David Sodman4a36e932017-11-07 14:29:47 -08002031 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002032
2033 {
2034 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002035 if (mTexturePool.size() < mTexturePoolSize) {
2036 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002037 const size_t offset = mTexturePool.size();
2038 mTexturePool.resize(mTexturePoolSize);
2039 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2040 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002041 } else if (mTexturePool.size() > mTexturePoolSize) {
2042 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2043 const size_t offset = mTexturePoolSize;
2044 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2045 mTexturePool.resize(mTexturePoolSize);
2046 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002047 }
2048 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002049
Ady Abrahambe0f9482019-04-24 15:41:53 -07002050 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002051 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002052
Kevin DuBois413287f2019-02-25 08:46:47 -08002053 if (mLumaSampling && mRegionSamplingThread) {
2054 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002055 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002056
2057 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2058 // side-effect of getTotalSize(), so we check that again here
2059 if (ATRACE_ENABLED()) {
2060 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2061 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062}
2063
Vishnu Nair4351ad52019-02-11 14:13:02 -08002064void SurfaceFlinger::computeLayerBounds() {
2065 for (const auto& pair : mDisplays) {
2066 const auto& displayDevice = pair.second;
2067 const auto display = displayDevice->getCompositionDisplay();
2068 for (const auto& layer : mDrawingState.layersSortedByZ) {
2069 // only consider the layers on the given layer stack
2070 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002071 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002072 }
2073
2074 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2075 }
2076 }
2077}
2078
Mathias Agopiancd60f992012-08-16 16:28:27 -07002079void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 ATRACE_CALL();
2081 ALOGV("rebuildLayerStacks");
2082
Mathias Agopiancd60f992012-08-16 16:28:27 -07002083 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002084 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002085 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002086 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002087
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002088 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002089 const auto& displayDevice = pair.second;
2090 auto display = displayDevice->getCompositionDisplay();
2091 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002092 Region opaqueRegion;
2093 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002094 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002095 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002096 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 const ui::Transform& tr = displayState.transform;
2098 const Rect bounds = displayState.bounds;
2099 if (displayState.isEnabled) {
2100 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002101
Jeff Sharkey76488112017-02-27 14:15:18 -07002102 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002103 auto compositionLayer = layer->getCompositionLayer();
2104 if (compositionLayer == nullptr) {
2105 return;
2106 }
2107
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002109 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2110 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2111
Lloyd Pique07e33212018-12-18 16:33:37 -08002112 bool needsOutputLayer = false;
2113
Lloyd Piqueef36b002019-01-23 17:52:04 -08002114 if (display->belongsInOutput(layer->getLayerStack(),
2115 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002116 Region drawRegion(tr.transform(
2117 layer->visibleNonTransparentRegion));
2118 drawRegion.andSelf(bounds);
2119 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002120 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002121 }
Chia-I Wu83806892017-11-16 10:50:20 -08002122 }
2123
Lloyd Pique07e33212018-12-18 16:33:37 -08002124 if (needsOutputLayer) {
2125 layersSortedByZ.emplace_back(
2126 display->getOrCreateOutputLayer(displayId, compositionLayer,
2127 layerFE));
2128 deprecated_layersSortedByZ.add(layer);
2129
2130 auto& outputLayerState = layersSortedByZ.back()->editState();
2131 outputLayerState.visibleRegion =
2132 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2133 } else if (displayId) {
2134 // For layers that are being removed from a HWC display,
2135 // and that have queued frames, add them to a a list of
2136 // released layers so we can properly set a fence.
2137 bool hasExistingOutputLayer =
2138 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2139 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2140 mLayersWithQueuedFrames.cend(),
2141 layer) != mLayersWithQueuedFrames.cend();
2142
2143 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002144 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002145 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002146 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002147 });
2148 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002149
2150 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002151 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002152
2153 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002154
2155 Region undefinedRegion{bounds};
2156 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2157
2158 display->editState().undefinedRegion = undefinedRegion;
2159 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002160 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002161 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002162}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164void SurfaceFlinger::postFrame()
2165{
2166 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002167 const auto display = getDefaultDisplayDeviceLocked();
2168 if (display && getHwComposer().isConnected(*display->getId())) {
2169 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2171 logFrameStats();
2172 }
2173 }
2174}
2175
Mathias Agopian87baae12012-07-31 12:38:26 -07002176void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177{
Mathias Agopian841cde52012-03-01 15:44:37 -08002178 ATRACE_CALL();
2179
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002180 // here we keep a copy of the drawing state (that is the state that's
2181 // going to be overwritten by handleTransactionLocked()) outside of
2182 // mStateLock so that the side-effects of the State assignment
2183 // don't happen with mStateLock held (which can cause deadlocks).
2184 State drawingState(mDrawingState);
2185
Mathias Agopianca4d3602011-05-19 15:38:14 -07002186 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002187 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188
Mathias Agopianca4d3602011-05-19 15:38:14 -07002189 // Here we're guaranteed that some transaction flags are set
2190 // so we can call handleTransactionLocked() unconditionally.
2191 // We call getTransactionFlags(), which will also clear the flags,
2192 // with mStateLock held to guarantee that mCurrentState won't change
2193 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002194
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002195 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002196 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002197 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002198
Mathias Agopianca4d3602011-05-19 15:38:14 -07002199 mDebugInTransaction = 0;
2200 invalidateHwcGeometry();
2201 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002202}
2203
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2205 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002206 const std::optional<DisplayIdentificationInfo> info =
2207 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002208
Dominik Laskowski075d3172018-05-24 15:50:06 -07002209 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002210 continue;
2211 }
2212
Lloyd Piqueba04e622017-12-14 17:11:26 -08002213 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002214 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002215 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002216 mPhysicalDisplayTokens[info->id] = new BBinder();
2217 DisplayDeviceState state;
2218 state.displayId = info->id;
2219 state.isSecure = true; // All physical displays are currently considered secure.
2220 state.displayName = info->name;
2221 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2222 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002223 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002225 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002226
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2228 if (index >= 0) {
2229 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2230 mInterceptor->saveDisplayDeletion(state.sequenceId);
2231 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002232 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002233 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234 }
2235
2236 processDisplayChangesLocked();
2237 }
2238
2239 mPendingHotplugEvents.clear();
2240}
2241
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002242void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002243 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2244 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002245}
2246
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002249 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002250 const sp<IGraphicBufferProducer>& producer) {
2251 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002252 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002253 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002254 creationArgs.isSecure = state.isSecure;
2255 creationArgs.displaySurface = dispSurface;
2256 creationArgs.hasWideColorGamut = false;
2257 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002258 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002259
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002260 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002261 creationArgs.isPrimary = isInternalDisplay;
2262
2263 if (useColorManagement && displayId) {
2264 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002266 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002267 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269
Dominik Laskowski7e045462018-05-30 13:02:02 -07002270 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002272 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 }
tangrobin6753a022018-08-10 10:58:54 +08002274 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275
Dominik Laskowski075d3172018-05-24 15:50:06 -07002276 if (displayId) {
2277 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002278 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002280 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002281
Lloyd Pique90c115d2018-09-18 21:39:42 -07002282 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002284 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 // Make sure that composition can never be stalled by a virtual display
2287 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002288 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002289 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2291 }
2292
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 creationArgs.displayInstallOrientation =
2294 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002295
Lloyd Pique99d3da52018-01-22 17:48:03 -08002296 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002297 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298
Lloyd Pique90c115d2018-09-18 21:39:42 -07002299 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300
2301 if (maxFrameBufferAcquiredBuffers >= 3) {
2302 nativeWindowSurface->preallocateBuffers();
2303 }
2304
2305 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002307 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002309 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002311 display->getCompositionDisplay()->setColorProfile(
2312 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2313 RenderIntent::COLORIMETRIC,
2314 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002315 if (!state.isVirtual()) {
2316 LOG_ALWAYS_FATAL_IF(!displayId);
2317 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002318 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320 display->setLayerStack(state.layerStack);
2321 display->setProjection(state.orientation, state.viewport, state.frame);
2322 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002324 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325}
2326
Lloyd Pique347200f2017-12-14 17:00:15 -08002327void SurfaceFlinger::processDisplayChangesLocked() {
2328 // here we take advantage of Vector's copy-on-write semantics to
2329 // improve performance by skipping the transaction entirely when
2330 // know that the lists are identical
2331 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2332 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2333 if (!curr.isIdenticalTo(draw)) {
2334 mVisibleRegionsDirty = true;
2335 const size_t cc = curr.size();
2336 size_t dc = draw.size();
2337
2338 // find the displays that were removed
2339 // (ie: in drawing state but not in current state)
2340 // also handle displays that changed
2341 // (ie: displays that are in both lists)
2342 for (size_t i = 0; i < dc;) {
2343 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2344 if (j < 0) {
2345 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002347 // Save display ID before disconnecting.
2348 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002349 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002350
2351 if (!display->isVirtual()) {
2352 LOG_ALWAYS_FATAL_IF(!displayId);
2353 dispatchDisplayHotplugEvent(displayId->value, false);
2354 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002356
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002357 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 } else {
2359 // this display is in both lists. see if something changed.
2360 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002362 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2363 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2364 if (state_binder != draw_binder) {
2365 // changing the surface is like destroying and
2366 // recreating the DisplayDevice, so we just remove it
2367 // from the drawing state, so that it get re-added
2368 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002370 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002372 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002373 mDrawingState.displays.removeItemsAt(i);
2374 dc--;
2375 // at this point we must loop to the next item
2376 continue;
2377 }
2378
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002382 }
2383 if ((state.orientation != draw[i].orientation) ||
2384 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002386 }
2387 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389 }
2390 }
2391 }
2392 ++i;
2393 }
2394
2395 // find displays that were added
2396 // (ie: in current state but not in drawing state)
2397 for (size_t i = 0; i < cc; i++) {
2398 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2399 const DisplayDeviceState& state(curr[i]);
2400
Lloyd Pique542307f2018-10-19 13:24:08 -07002401 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 sp<IGraphicBufferProducer> producer;
2403 sp<IGraphicBufferProducer> bqProducer;
2404 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002405 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002408 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 // Virtual displays without a surface are dormant:
2410 // they have external state (layer stack, projection,
2411 // etc.) but no internal state (i.e. a DisplayDevice).
2412 if (state.surface != nullptr) {
2413 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 int width = 0;
2416 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2417 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2418 int height = 0;
2419 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2420 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2421 int intFormat = 0;
2422 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2423 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002424 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 displayId =
2427 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002428 }
2429
2430 // TODO: Plumb requested format back up to consumer
2431
2432 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 bqProducer, bqConsumer,
2435 state.displayName);
2436
2437 dispSurface = vds;
2438 producer = vds;
2439 }
2440 } else {
2441 ALOGE_IF(state.surface != nullptr,
2442 "adding a supported display, but rendering "
2443 "surface is provided (%p), ignoring it",
2444 state.surface.get());
2445
Dominik Laskowski075d3172018-05-24 15:50:06 -07002446 displayId = state.displayId;
2447 LOG_ALWAYS_FATAL_IF(!displayId);
2448 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 producer = bqProducer;
2450 }
2451
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002454 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002455 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002456 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002457 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002459 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 }
2461 }
2462 }
2463 }
2464 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465
2466 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002467}
2468
Mathias Agopian87baae12012-07-31 12:38:26 -07002469void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002470{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002471 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2472
Dan Stoza7dde5992015-05-22 09:51:44 -07002473 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002474 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2475 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002476 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002477
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 /*
2479 * Traversal of the children
2480 * (perform the transaction for each of them if needed)
2481 */
2482
Marissa Wall06255332019-03-27 13:48:27 -07002483 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002484 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002486 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
2488 const uint32_t flags = layer->doTransaction(0);
2489 if (flags & Layer::eVisibleRegion)
2490 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002491
2492 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002493 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002494 }
Robert Carr2047fae2016-11-28 14:09:09 -08002495 });
Marissa Wall06255332019-03-27 13:48:27 -07002496 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 }
2498
2499 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 */
2502
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002505 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002508 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002509 // The transform hint might have changed for some layers
2510 // (either because a display has changed, or because a layer
2511 // as changed).
2512 //
2513 // Walk through all the layers in currentLayers,
2514 // and update their transform hint.
2515 //
2516 // If a layer is visible only on a single display, then that
2517 // display is used to calculate the hint, otherwise we use the
2518 // default display.
2519 //
2520 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2521 // the hint is set before we acquire a buffer from the surface texture.
2522 //
2523 // NOTE: layer transactions have taken place already, so we use their
2524 // drawing state. However, SurfaceFlinger's own transaction has not
2525 // happened yet, so we must use the current state layer list
2526 // (soon to become the drawing state list).
2527 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002528 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002529 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002530 bool first = true;
2531 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002532 // NOTE: we rely on the fact that layers are sorted by
2533 // layerStack first (so we don't have to traverse the list
2534 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002536 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002537 currentlayerStack = layerStack;
2538 // figure out if this layerstack is mirrored
2539 // (more than one display) if so, pick the default display,
2540 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 hintDisplay = nullptr;
2542 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002543 if (display->getCompositionDisplay()
2544 ->belongsInOutput(layer->getLayerStack(),
2545 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 if (hintDisplay) {
2547 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002548 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002550 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002551 }
2552 }
2553 }
2554 }
Chet Haase91d25932013-04-11 15:24:55 -07002555
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002556 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002557 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2558 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002559
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002560 // could be null when this layer is using a layerStack
2561 // that is not visible on any display. Also can occur at
2562 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002563 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002564 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002565
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002566 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002567 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002568 if (hintDisplay) {
2569 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002570 }
Robert Carr2047fae2016-11-28 14:09:09 -08002571
2572 first = false;
2573 });
Mathias Agopian84300952012-11-21 16:02:13 -08002574 }
2575
2576
Mathias Agopian3559b072012-08-15 13:46:03 -07002577 /*
2578 * Perform our own transaction if needed
2579 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580
2581 if (mLayersAdded) {
2582 mLayersAdded = false;
2583 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002584 mVisibleRegionsDirty = true;
2585 }
2586
2587 // some layers might have been removed, so
2588 // we need to update the regions they're exposing.
2589 if (mLayersRemoved) {
2590 mLayersRemoved = false;
2591 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002592 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002593 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002596 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002597 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002598 }
Robert Carr2047fae2016-11-28 14:09:09 -08002599 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 }
2601
Vishnu Nairec0ab382019-02-13 15:32:56 -08002602 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002604}
2605
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002606void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002607 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002608 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002609 return;
2610 }
2611
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002612 if (mVisibleRegionsDirty || mInputInfoChanged) {
2613 mInputInfoChanged = false;
2614 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002615 } else if (mInputWindowCommands.syncInputWindows) {
2616 // If the caller requested to sync input windows, but there are no
2617 // changes to input windows, notify immediately.
2618 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002619 }
2620
2621 executeInputWindowCommands();
2622}
2623
2624void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002625 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002626
2627 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2628 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002629 // When calculating the screen bounds we ignore the transparent region since it may
2630 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002631 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002632 }
2633 });
chaviw291d88a2019-02-14 10:33:58 -08002634
2635 mInputFlinger->setInputWindows(inputHandles,
2636 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2637 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002638}
2639
Vishnu Nairec0ab382019-02-13 15:32:56 -08002640void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002641 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002642 mPendingInputWindowCommands.clear();
2643}
2644
chaviwfbe5d9c2018-12-26 12:23:37 -08002645void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002646 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2647 if (transferTouchFocusCommand.fromToken != nullptr &&
2648 transferTouchFocusCommand.toToken != nullptr &&
2649 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2650 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2651 transferTouchFocusCommand.toToken);
2652 }
2653 }
2654
2655 mInputWindowCommands.clear();
2656}
2657
Riley Andrews03414a12014-07-01 14:22:59 -07002658void SurfaceFlinger::updateCursorAsync()
2659{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002660 compositionengine::CompositionRefreshArgs refreshArgs;
2661 for (const auto& [_, display] : mDisplays) {
2662 if (display->getId()) {
2663 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002664 }
2665 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002666
2667 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002668}
2669
2670void SurfaceFlinger::commitTransaction()
2671{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002672 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002673 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 for (const auto& l : mLayersPendingRemoval) {
2675 recordBufferingStats(l->getName().string(),
2676 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002677
Lloyd Pique07e33212018-12-18 16:33:37 -08002678 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002679 if (l->isRemovedFromCurrentState()) {
chaviw49a108c2019-08-12 11:23:06 -07002680 l->latchAndReleaseBuffer();
Robert Carr2e102c92018-10-23 12:11:15 -07002681 }
chaviw74d90ad2019-04-26 14:45:26 -07002682
2683 // If the layer has been removed and has no parent, then it will not be reachable
2684 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2685 // ensure we can copy its current to drawing state.
2686 if (!l->getParent()) {
2687 mOffscreenLayers.emplace(l.get());
2688 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 }
2690 mLayersPendingRemoval.clear();
2691 }
2692
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002693 // If this transaction is part of a window animation then the next frame
2694 // we composite should be considered an animation as well.
2695 mAnimCompositionPending = mAnimTransactionPending;
2696
Nataniel Borges2b796da2019-02-15 13:32:18 -08002697 withTracingLock([&]() {
2698 mDrawingState = mCurrentState;
2699 // clear the "changed" flags in current state
2700 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002701
chaviw74d90ad2019-04-26 14:45:26 -07002702 mDrawingState.traverseInZOrder([&](Layer* layer) {
2703 layer->commitChildList();
2704
2705 // If the layer can be reached when traversing mDrawingState, then the layer is no
2706 // longer offscreen. Remove the layer from the offscreenLayer set.
2707 if (mOffscreenLayers.count(layer)) {
2708 mOffscreenLayers.erase(layer);
2709 }
2710 });
2711
2712 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002714
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002715 mTransactionPending = false;
2716 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718}
2719
Nataniel Borges2b796da2019-02-15 13:32:18 -08002720void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2721 if (mTracingEnabledChanged) {
2722 mTracingEnabled = mTracing.isEnabled();
2723 mTracingEnabledChanged = false;
2724 }
2725
2726 // Synchronize with Tracing thread
2727 std::unique_lock<std::mutex> lock;
2728 if (mTracingEnabled) {
2729 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2730 }
2731
2732 lockedOperation();
2733
2734 // Synchronize with Tracing thread
2735 if (mTracingEnabled) {
2736 lock.unlock();
2737 }
2738}
2739
chaviw74d90ad2019-04-26 14:45:26 -07002740void SurfaceFlinger::commitOffscreenLayers() {
2741 for (Layer* offscreenLayer : mOffscreenLayers) {
2742 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2743 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2744 if (!trFlags) return;
2745
2746 layer->doTransaction(0);
2747 layer->commitChildList();
2748 });
2749 }
2750}
2751
Lloyd Pique32cbe282018-10-19 13:09:22 -07002752void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002753 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002754 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002756
Lloyd Pique32cbe282018-10-19 13:09:22 -07002757 auto display = displayDevice->getCompositionDisplay();
2758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 Region aboveOpaqueLayers;
2760 Region aboveCoveredLayers;
2761 Region dirty;
2762
Mathias Agopian87baae12012-07-31 12:38:26 -07002763 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764
Robert Carr2047fae2016-11-28 14:09:09 -08002765 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002766 // start with the whole surface at its current location
2767 const Layer::State& s(layer->getDrawingState());
2768
Jesse Hall01e29052013-02-19 16:13:35 -08002769 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08002770 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002771 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002773
Mathias Agopianab028732010-03-16 16:41:46 -07002774 /*
2775 * opaqueRegion: area of a surface that is fully opaque.
2776 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002778
2779 /*
2780 * visibleRegion: area of a surface that is visible on screen
2781 * and not fully transparent. This is essentially the layer's
2782 * footprint minus the opaque regions above it.
2783 * Areas covered by a translucent surface are considered visible.
2784 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002786
2787 /*
2788 * coveredRegion: area of a surface that is covered by all
2789 * visible regions above it (which includes the translucent areas).
2790 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002792
Jesse Halla8026d22012-09-25 13:25:04 -07002793 /*
2794 * transparentRegion: area of a surface that is hinted to be completely
2795 * transparent. This is only used to tell when the layer has no visible
2796 * non-transparent regions and can be removed from the layer list. It
2797 * does not affect the visibleRegion of this layer or any layers
2798 * beneath it. The hint may not be correct if apps don't respect the
2799 * SurfaceView restrictions (which, sadly, some don't).
2800 */
2801 Region transparentRegion;
2802
Mathias Agopianab028732010-03-16 16:41:46 -07002803
2804 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002805 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002806 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002807 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002808
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002810 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002811 if (!visibleRegion.isEmpty()) {
2812 // Remove the transparent area from the visible region
2813 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002814 if (tr.preserveRects()) {
2815 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002816 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002817 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002818 // transformation too complex, can't do the
2819 // transparent region optimization.
2820 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002821 }
Mathias Agopianab028732010-03-16 16:41:46 -07002822 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823
Mathias Agopianab028732010-03-16 16:41:46 -07002824 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002825 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002826 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002827 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002828 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002829 // the opaque region is the layer's footprint
2830 opaqueRegion = visibleRegion;
2831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 }
2833 }
2834
Robert Carre5f4f692018-01-12 13:12:28 -08002835 if (visibleRegion.isEmpty()) {
2836 layer->clearVisibilityRegions();
2837 return;
2838 }
2839
Mathias Agopianab028732010-03-16 16:41:46 -07002840 // Clip the covered region to the visible region
2841 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2842
2843 // Update aboveCoveredLayers for next (lower) layer
2844 aboveCoveredLayers.orSelf(visibleRegion);
2845
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 // subtract the opaque region covered by the layers above us
2847 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
2849 // compute this layer's dirty region
2850 if (layer->contentDirty) {
2851 // we need to invalidate the whole region
2852 dirty = visibleRegion;
2853 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002854 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 layer->contentDirty = false;
2856 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002857 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002858 * the exposed region consists of two components:
2859 * 1) what's VISIBLE now and was COVERED before
2860 * 2) what's EXPOSED now less what was EXPOSED before
2861 *
2862 * note that (1) is conservative, we start with the whole
2863 * visible region but only keep what used to be covered by
2864 * something -- which mean it may have been exposed.
2865 *
2866 * (2) handles areas that were not covered by anything but got
2867 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002868 */
Mathias Agopianab028732010-03-16 16:41:46 -07002869 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002870 const Region oldVisibleRegion = layer->visibleRegion;
2871 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002872 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2873 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
2875 dirty.subtractSelf(aboveOpaqueLayers);
2876
2877 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002878 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879
Mathias Agopianab028732010-03-16 16:41:46 -07002880 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002882
Jesse Halla8026d22012-09-25 13:25:04 -07002883 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 layer->setVisibleRegion(visibleRegion);
2885 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002886 layer->setVisibleNonTransparentRegion(
2887 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002888 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889
Mathias Agopian87baae12012-07-31 12:38:26 -07002890 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Chia-I Wuab0c3192017-08-01 11:29:00 -07002893void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002894 for (const auto& [token, displayDevice] : mDisplays) {
2895 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002896 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002897 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002898 }
2899 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002900}
2901
Dan Stoza6b9454d2014-11-07 16:00:59 -08002902bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903{
Ady Abraham09bd3922019-04-08 10:44:56 -07002904 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 ALOGV("handlePageFlip");
2906
Brian Andersond6927fb2016-07-23 23:37:30 -07002907 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908
Mathias Agopian4fec8732012-06-29 14:12:52 -07002909 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002910 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002911 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002912
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002913 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2914
Eric Penner51c59cd2014-07-28 19:51:58 -07002915 // Store the set of layers that need updates. This set must not change as
2916 // buffers are being latched, as this could result in a deadlock.
2917 // Example: Two producers share the same command stream and:
2918 // 1.) Layer 0 is latched
2919 // 2.) Layer 0 gets a new frame
2920 // 2.) Layer 1 gets a new frame
2921 // 3.) Layer 1 is latched.
2922 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2923 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002924 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002925 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002926 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002927 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002928 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002929 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002930 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002931 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 } else {
2934 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 }
Robert Carr2047fae2016-11-28 14:09:09 -08002936 });
2937
chaviw49a108c2019-08-12 11:23:06 -07002938 // The client can continue submitting buffers for offscreen layers, but they will not
2939 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2940 // layers to ensure dequeueBuffer doesn't block indefinitely.
2941 for (Layer* offscreenLayer : mOffscreenLayers) {
2942 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2943 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2944 }
2945
Lloyd Piquef2c79392018-12-20 16:23:33 -08002946 if (!mLayersWithQueuedFrames.empty()) {
2947 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2948 // writes to Layer current state. See also b/119481871
2949 Mutex::Autolock lock(mStateLock);
2950
2951 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002952 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002953 mLayersPendingRefresh.push_back(layer);
2954 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002955 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002956 if (layer->isBufferLatched()) {
2957 newDataLatched = true;
2958 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002959 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002960 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002961
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002962 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002963
2964 // If we will need to wake up at some time in the future to deal with a
2965 // queued frame that shouldn't be displayed during this vsync period, wake
2966 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002967 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002968 signalLayerUpdate();
2969 }
2970
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002971 // enter boot animation on first buffer latch
2972 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2973 ALOGI("Enter boot animation");
2974 mBootStage = BootStage::BOOTANIMATION;
2975 }
2976
Dan Stoza6b9454d2014-11-07 16:00:59 -08002977 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002978 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979}
2980
Mathias Agopianad456f92011-01-13 17:53:01 -08002981void SurfaceFlinger::invalidateHwcGeometry()
2982{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002984}
2985
Robert Carrc0df3122019-04-11 13:18:21 -07002986status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2987 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2988 const sp<IBinder>& parentHandle,
2989 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002990 // add this layer to the current state list
2991 {
2992 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002993 sp<Layer> parent;
2994 if (parentHandle != nullptr) {
2995 parent = fromHandle(parentHandle);
2996 if (parent == nullptr) {
2997 return NAME_NOT_FOUND;
2998 }
2999 } else {
3000 parent = parentLayer;
3001 }
3002
Robert Carr1f0a16a2016-10-24 16:27:39 -07003003 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003004 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003005 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003006 return NO_MEMORY;
3007 }
Robert Carrc0df3122019-04-11 13:18:21 -07003008
3009 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3010
Robert Carrb89ea9d2018-12-10 13:01:14 -08003011 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003013 } else if (parent == nullptr) {
3014 lbc->onRemovedFromCurrentState();
3015 } else if (parent->isRemovedFromCurrentState()) {
3016 parent->addChild(lbc);
3017 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003018 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 parent->addChild(lbc);
3020 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003021
Yiwei Zhang243b3782018-05-15 17:40:04 -07003022 if (gbc != nullptr) {
3023 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3024 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3025 mMaxGraphicBufferProducerListSize,
3026 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3027 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003028 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003029 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003030 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003031 }
3032
Mathias Agopian96f08192010-06-02 23:28:45 -07003033 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003034 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003037}
3038
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003039uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003040 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003041}
3042
Mathias Agopian3f844832013-08-07 21:24:32 -07003043uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003044 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045}
3046
Mathias Agopian3f844832013-08-07 21:24:32 -07003047uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003048 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003049}
3050
3051uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003052 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003053 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003054 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003056 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 }
3058 return old;
3059}
3060
Marissa Wall713b63f2018-10-17 15:42:43 -07003061bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003062 // to prevent onHandleDestroyed from being called while the lock is held,
3063 // we must keep a copy of the transactions (specifically the composer
3064 // states) around outside the scope of the lock
3065 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003066 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003067 {
3068 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003069
Valerie Haufce31b82019-04-30 16:41:14 -07003070 auto it = mTransactionQueues.begin();
3071 while (it != mTransactionQueues.end()) {
3072 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003073
Valerie Haufce31b82019-04-30 16:41:14 -07003074 while (!transactionQueue.empty()) {
3075 const auto& transaction = transactionQueue.front();
3076 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003077 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003078 transaction.states)) {
3079 setTransactionFlags(eTransactionFlushNeeded);
3080 break;
3081 }
3082 transactions.push_back(transaction);
3083 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3084 mPendingInputWindowCommands, transaction.desiredPresentTime,
3085 transaction.buffer, transaction.callback,
3086 transaction.postTime, transaction.privileged,
3087 /*isMainThread*/ true);
3088 transactionQueue.pop();
3089 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003090 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003091
Valerie Haufce31b82019-04-30 16:41:14 -07003092 if (transactionQueue.empty()) {
3093 it = mTransactionQueues.erase(it);
3094 mTransactionCV.broadcast();
3095 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003096 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003097 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003098 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003099 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003100 return flushedATransaction;
3101}
3102
3103bool SurfaceFlinger::transactionFlushNeeded() {
3104 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003105}
3106
chaviwca27f252018-02-06 16:46:39 -08003107
Marissa Wall17b4e452018-12-26 16:32:34 -08003108bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003109 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003110 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003111 if (!useCachedExpectedPresentTime)
3112 populateExpectedPresentTime();
3113
3114 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003115 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3116 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3117 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3118 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3119 return false;
3120 }
3121
Marissa Wall713b63f2018-10-17 15:42:43 -07003122 for (const ComposerState& state : states) {
3123 const layer_state_t& s = state.state;
3124 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3125 continue;
3126 }
3127 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003128 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003129 }
3130 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003131 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003132}
3133
3134void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3135 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003136 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003137 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003138 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003139 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003140 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003141 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003142
Valerie Haubc6ddb12019-03-08 11:10:15 -08003143 const int64_t postTime = systemTime();
3144
Robert Carr14167e02019-02-13 13:50:55 -08003145 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3146
Mathias Agopian698c0872011-06-28 19:09:31 -07003147 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003148
Marissa Wall713b63f2018-10-17 15:42:43 -07003149 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003150 auto itr = mTransactionQueues.find(applyToken);
3151 // if this is an animation frame, wait until prior animation frame has
3152 // been applied by SF
3153 if (flags & eAnimation) {
3154 while (itr != mTransactionQueues.end()) {
3155 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3156 if (CC_UNLIKELY(err != NO_ERROR)) {
3157 ALOGW_IF(err == TIMED_OUT,
3158 "setTransactionState timed out "
3159 "waiting for animation frame to apply");
3160 break;
3161 }
3162 itr = mTransactionQueues.find(applyToken);
3163 }
3164 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003165
3166 // Expected present time is computed and cached on invalidate, so it may be stale.
3167 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3168 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003169 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003170 uncacheBuffer, listenerCallbacks, postTime,
3171 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003172 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003173 return;
3174 }
3175
Valerie Haubc6ddb12019-03-08 11:10:15 -08003176 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003177 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003178}
3179
3180void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003181 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003182 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003183 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003184 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003185 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003186 const int64_t postTime, bool privileged,
3187 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003188 uint32_t transactionFlags = 0;
3189
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003190 if (flags & eAnimation) {
3191 // For window updates that are part of an animation we must wait for
3192 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003193 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003194 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003195 if (CC_UNLIKELY(err != NO_ERROR)) {
3196 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003197 // caller after a few seconds.
3198 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3199 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003200 mAnimTransactionPending = false;
3201 break;
3202 }
3203 }
3204 }
3205
chaviwca27f252018-02-06 16:46:39 -08003206 for (const DisplayState& display : displays) {
3207 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003208 }
3209
Marissa Walld600d572019-03-26 15:38:50 -07003210 // In case the client has sent a Transaction that should receive callbacks but without any
3211 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3212 // to the callback thread so it can send an empty callback
3213 if (!listenerCallbacks.empty()) {
3214 mTransactionCompletedThread.run();
3215 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003216 for (const auto& listenerCallback : listenerCallbacks) {
3217 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003218 }
3219
Marissa Walle2ffb422018-10-12 11:33:52 -07003220 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003221 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003222 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3223 postTime, privileged);
3224 }
3225
Marissa Wallefb71af2019-06-27 14:45:53 -07003226 for (const auto& listenerCallback : listenerCallbacks) {
3227 mTransactionCompletedThread.endRegistration(listenerCallback);
3228 }
3229
Marissa Walle2ffb422018-10-12 11:33:52 -07003230 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003231 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003232 mTransactionCompletedThread.sendCallbacks();
3233 }
3234 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003235
chaviw273171b2018-12-26 11:46:30 -08003236 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3237
Marissa Wall947d34e2019-03-29 14:03:53 -07003238 if (uncacheBuffer.isValid()) {
3239 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003240 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003241 }
3242
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003243 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3244 // anyway. This can be used as a flush mechanism for previous async transactions.
3245 // Empty animation transaction can be used to simulate back-pressure, so also force a
3246 // transaction for empty animation transactions.
3247 if (transactionFlags == 0 &&
3248 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003249 transactionFlags = eTransactionNeeded;
3250 }
3251
Marissa Wall06255332019-03-27 13:48:27 -07003252 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3253 // so we don't have to wake up again next frame to preform an uneeded traversal.
3254 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3255 transactionFlags = transactionFlags & (~eTraversalNeeded);
3256 mTraversalNeededMainThread = true;
3257 }
3258
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003260 if (mInterceptor->isEnabled()) {
3261 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003262 }
Irvel468051e2016-06-13 16:44:44 -07003263
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003265 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3266 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003267 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003268
3269 // if this is a synchronous transaction, wait for it to take effect
3270 // before returning.
3271 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003273 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003274 if (flags & eAnimation) {
3275 mAnimTransactionPending = true;
3276 }
chaviw4fe36852019-04-15 16:25:49 -07003277 if (mPendingInputWindowCommands.syncInputWindows) {
3278 mPendingSyncInputWindows = true;
3279 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003280
3281 // applyTransactionState can be called by either the main SF thread or by
3282 // another process through setTransactionState. While a given process may wish
3283 // to wait on synchronous transactions, the main SF thread should never
3284 // be blocked. Therefore, we only wait if isMainThread is false.
3285 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003286 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3287 if (CC_UNLIKELY(err != NO_ERROR)) {
3288 // just in case something goes wrong in SF, return to the
3289 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003290 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3291 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003292 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003293 break;
3294 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003295 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296 }
3297}
3298
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003299uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3300 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3301 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003302
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003304 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3305
3306 const uint32_t what = s.what;
3307 if (what & DisplayState::eSurfaceChanged) {
3308 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3309 state.surface = s.surface;
3310 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003311 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003312 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003313 if (what & DisplayState::eLayerStackChanged) {
3314 if (state.layerStack != s.layerStack) {
3315 state.layerStack = s.layerStack;
3316 flags |= eDisplayTransactionNeeded;
3317 }
3318 }
3319 if (what & DisplayState::eDisplayProjectionChanged) {
3320 if (state.orientation != s.orientation) {
3321 state.orientation = s.orientation;
3322 flags |= eDisplayTransactionNeeded;
3323 }
3324 if (state.frame != s.frame) {
3325 state.frame = s.frame;
3326 flags |= eDisplayTransactionNeeded;
3327 }
3328 if (state.viewport != s.viewport) {
3329 state.viewport = s.viewport;
3330 flags |= eDisplayTransactionNeeded;
3331 }
3332 }
3333 if (what & DisplayState::eDisplaySizeChanged) {
3334 if (state.width != s.width) {
3335 state.width = s.width;
3336 flags |= eDisplayTransactionNeeded;
3337 }
3338 if (state.height != s.height) {
3339 state.height = s.height;
3340 flags |= eDisplayTransactionNeeded;
3341 }
3342 }
3343
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344 return flags;
3345}
3346
Robert Carr14167e02019-02-13 13:50:55 -08003347bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003348 IPCThreadState* ipc = IPCThreadState::self();
3349 const int pid = ipc->getCallingPid();
3350 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003351 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003352 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003353 return false;
3354 }
3355 return true;
3356}
3357
Marissa Wall3dad52d2019-03-22 14:03:19 -07003358uint32_t SurfaceFlinger::setClientStateLocked(
3359 const ComposerState& composerState, int64_t desiredPresentTime,
3360 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3361 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003362 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003363
Vishnu Nairf03652d2019-07-16 17:56:56 -07003364 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003365 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003366 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003367 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003368 new CallbackHandle(listenerCallback.transactionCompletedListener,
3369 listenerCallback.callbackIds, s.surface));
3370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 return 0;
3372 }
3373
chaviw8b3871a2017-11-01 17:41:01 -07003374 uint32_t flags = 0;
3375
Garfield Tan8a3083e2018-12-03 13:21:07 -08003376 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003377 bool geometryAppliesWithResize =
3378 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003379
3380 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3381 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003382 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003383 layer->pushPendingState();
3384 }
3385
chaviw8b3871a2017-11-01 17:41:01 -07003386 if (what & layer_state_t::ePositionChanged) {
3387 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3388 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003389 }
chaviw8b3871a2017-11-01 17:41:01 -07003390 }
3391 if (what & layer_state_t::eLayerChanged) {
3392 // NOTE: index needs to be calculated before we update the state
3393 const auto& p = layer->getParent();
3394 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003395 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003396 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003397 mCurrentState.layersSortedByZ.removeAt(idx);
3398 mCurrentState.layersSortedByZ.add(layer);
3399 // we need traversal (state changed)
3400 // AND transaction (list changed)
3401 flags |= eTransactionNeeded|eTraversalNeeded;
3402 }
chaviw8b3871a2017-11-01 17:41:01 -07003403 } else {
3404 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003405 flags |= eTransactionNeeded|eTraversalNeeded;
3406 }
3407 }
chaviw8b3871a2017-11-01 17:41:01 -07003408 }
3409 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003410 // NOTE: index needs to be calculated before we update the state
3411 const auto& p = layer->getParent();
3412 if (p == nullptr) {
3413 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3414 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3415 mCurrentState.layersSortedByZ.removeAt(idx);
3416 mCurrentState.layersSortedByZ.add(layer);
3417 // we need traversal (state changed)
3418 // AND transaction (list changed)
3419 flags |= eTransactionNeeded|eTraversalNeeded;
3420 }
3421 } else {
3422 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3423 flags |= eTransactionNeeded|eTraversalNeeded;
3424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 }
3426 }
3427 if (what & layer_state_t::eSizeChanged) {
3428 if (layer->setSize(s.w, s.h)) {
3429 flags |= eTraversalNeeded;
3430 }
3431 }
3432 if (what & layer_state_t::eAlphaChanged) {
3433 if (layer->setAlpha(s.alpha))
3434 flags |= eTraversalNeeded;
3435 }
3436 if (what & layer_state_t::eColorChanged) {
3437 if (layer->setColor(s.color))
3438 flags |= eTraversalNeeded;
3439 }
Peiyong Lind3788632018-09-18 16:01:31 -07003440 if (what & layer_state_t::eColorTransformChanged) {
3441 if (layer->setColorTransform(s.colorTransform)) {
3442 flags |= eTraversalNeeded;
3443 }
3444 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003445 if (what & layer_state_t::eBackgroundColorChanged) {
3446 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3447 flags |= eTraversalNeeded;
3448 }
3449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003451 // TODO: b/109894387
3452 //
3453 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3454 // rotation. To see the problem observe that if we have a square parent, and a child
3455 // of the same size, then we rotate the child 45 degrees around it's center, the child
3456 // must now be cropped to a non rectangular 8 sided region.
3457 //
3458 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3459 // private API, and the WindowManager only uses rotation in one case, which is on a top
3460 // level layer in which cropping is not an issue.
3461 //
3462 // However given that abuse of rotation matrices could lead to surfaces extending outside
3463 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3464 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3465 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003466 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003467 flags |= eTraversalNeeded;
3468 }
3469 if (what & layer_state_t::eTransparentRegionChanged) {
3470 if (layer->setTransparentRegionHint(s.transparentRegion))
3471 flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eFlagsChanged) {
3474 if (layer->setFlags(s.flags, s.mask))
3475 flags |= eTraversalNeeded;
3476 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003477 if (what & layer_state_t::eCropChanged_legacy) {
3478 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003479 flags |= eTraversalNeeded;
3480 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003481 if (what & layer_state_t::eCornerRadiusChanged) {
3482 if (layer->setCornerRadius(s.cornerRadius))
3483 flags |= eTraversalNeeded;
3484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 if (what & layer_state_t::eLayerStackChanged) {
3486 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3487 // We only allow setting layer stacks for top level layers,
3488 // everything else inherits layer stack from its parent.
3489 if (layer->hasParent()) {
3490 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3491 layer->getName().string());
3492 } else if (idx < 0) {
3493 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3494 "that also does not appear in the top level layer list. Something"
3495 " has gone wrong.", layer->getName().string());
3496 } else if (layer->setLayerStack(s.layerStack)) {
3497 mCurrentState.layersSortedByZ.removeAt(idx);
3498 mCurrentState.layersSortedByZ.add(layer);
3499 // we need traversal (state changed)
3500 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003501 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003502 }
3503 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003504 if (what & layer_state_t::eDeferTransaction_legacy) {
3505 if (s.barrierHandle_legacy != nullptr) {
3506 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3507 } else if (s.barrierGbp_legacy != nullptr) {
3508 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003509 if (authenticateSurfaceTextureLocked(gbp)) {
3510 const auto& otherLayer =
3511 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003512 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003513 } else {
3514 ALOGE("Attempt to defer transaction to to an"
3515 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003516 }
3517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 // We don't trigger a traversal here because if no other state is
3519 // changed, we don't want this to cause any more work
3520 }
chaviw8b3871a2017-11-01 17:41:01 -07003521 if (what & layer_state_t::eReparentChildren) {
3522 if (layer->reparentChildren(s.reparentHandle)) {
3523 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003524 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (what & layer_state_t::eDetachChildren) {
3527 layer->detachChildren();
3528 }
3529 if (what & layer_state_t::eOverrideScalingModeChanged) {
3530 layer->setOverrideScalingMode(s.overrideScalingMode);
3531 // We don't trigger a traversal here because if no other state is
3532 // changed, we don't want this to cause any more work
3533 }
Marissa Wall61c58622018-07-18 10:12:20 -07003534 if (what & layer_state_t::eTransformChanged) {
3535 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3536 }
3537 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3538 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3539 flags |= eTraversalNeeded;
3540 }
3541 if (what & layer_state_t::eCropChanged) {
3542 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3543 }
Marissa Wall861616d2018-10-22 12:52:23 -07003544 if (what & layer_state_t::eFrameChanged) {
3545 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3546 }
Marissa Wall61c58622018-07-18 10:12:20 -07003547 if (what & layer_state_t::eAcquireFenceChanged) {
3548 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3549 }
3550 if (what & layer_state_t::eDataspaceChanged) {
3551 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3552 }
3553 if (what & layer_state_t::eHdrMetadataChanged) {
3554 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3555 }
3556 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3557 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3558 }
3559 if (what & layer_state_t::eApiChanged) {
3560 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3561 }
3562 if (what & layer_state_t::eSidebandStreamChanged) {
3563 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3564 }
Robert Carr720e5062018-07-30 17:45:14 -07003565 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003566 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003567 layer->setInputInfo(s.inputInfo);
3568 flags |= eTraversalNeeded;
3569 } else {
3570 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3571 }
Robert Carr720e5062018-07-30 17:45:14 -07003572 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003573 if (what & layer_state_t::eMetadataChanged) {
3574 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3575 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003576 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3577 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3578 flags |= eTraversalNeeded;
3579 }
3580 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003581 // This has to happen after we reparent children because when we reparent to null we remove
3582 // child layers from current state and remove its relative z. If the children are reparented in
3583 // the same transaction, then we have to make sure we reparent the children first so we do not
3584 // lose its relative z order.
3585 if (what & layer_state_t::eReparent) {
3586 bool hadParent = layer->hasParent();
3587 if (layer->reparent(s.parentHandleForChild)) {
3588 if (!hadParent) {
3589 mCurrentState.layersSortedByZ.remove(layer);
3590 }
3591 flags |= eTransactionNeeded | eTraversalNeeded;
3592 }
3593 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003594 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07003595 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003596 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003597 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3598 }
3599 }
Marissa Wall78b72202019-03-15 14:58:34 -07003600 bool bufferChanged = what & layer_state_t::eBufferChanged;
3601 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3602 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003603 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003604 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003605 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3606 if (success) {
3607 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3608 success = ClientCache::getInstance()
3609 .registerErasedRecipient(s.cachedBuffer,
3610 wp<ClientCache::ErasedRecipient>(this));
3611 if (!success) {
3612 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3613 }
3614 }
Marissa Wall78b72202019-03-15 14:58:34 -07003615 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003616 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003617 } else if (bufferChanged) {
3618 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003619 }
Marissa Wall78b72202019-03-15 14:58:34 -07003620 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003621 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003622 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003623 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003624 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003625 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3626 // Do not put anything that updates layer state or modifies flags after
3627 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003628 return flags;
3629}
3630
chaviw273171b2018-12-26 11:46:30 -08003631uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3632 uint32_t flags = 0;
3633 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3634 flags |= eTraversalNeeded;
3635 }
3636
chaviwa911b102019-02-14 10:18:33 -08003637 if (inputWindowCommands.syncInputWindows) {
3638 flags |= eTraversalNeeded;
3639 }
3640
Vishnu Nairec0ab382019-02-13 15:32:56 -08003641 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003642 return flags;
3643}
3644
Marissa Wall2d814fb2019-04-09 18:52:57 +00003645status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3646 uint32_t h, PixelFormat format, uint32_t flags,
3647 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003648 sp<IGraphicBufferProducer>* gbp,
3649 const sp<IBinder>& parentHandle,
3650 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003651 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003652 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003653 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003654 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003655 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003656
Robert Carrc0df3122019-04-11 13:18:21 -07003657 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3658 "Expected only one of parentLayer or parentHandle to be non-null. "
3659 "Programmer error?");
3660
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003661 status_t result = NO_ERROR;
3662
3663 sp<Layer> layer;
3664
Cody Northropbc755282017-03-31 12:00:08 -06003665 String8 uniqueName = getUniqueLayerName(name);
3666
Evan Roskya1f1e152019-01-24 16:17:46 -08003667 bool primaryDisplayOnly = false;
3668
3669 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3670 // TODO b/64227542
3671 if (metadata.has(METADATA_WINDOW_TYPE)) {
3672 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3673 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003674 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003675 primaryDisplayOnly = true;
3676 }
3677 }
3678
Mathias Agopian3165cc22012-08-08 19:42:09 -07003679 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003680 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003681 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3682 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003683
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003685 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003686 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3687 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003688 break;
chaviw13fdc492017-06-27 12:40:18 -07003689 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003690 // check if buffer size is set for color layer.
3691 if (w > 0 || h > 0) {
3692 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3693 int(w), int(h));
3694 return BAD_VALUE;
3695 }
3696
Evan Roskya1f1e152019-01-24 16:17:46 -08003697 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3698 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003699 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003700 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003701 // check if buffer size is set for container layer.
3702 if (w > 0 || h > 0) {
3703 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3704 int(w), int(h));
3705 return BAD_VALUE;
3706 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003707 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3708 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003709 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003710 default:
3711 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 break;
3713 }
3714
Dan Stoza7d89d062015-04-30 13:29:25 -07003715 if (result != NO_ERROR) {
3716 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003718
Evan Roskya1f1e152019-01-24 16:17:46 -08003719 if (primaryDisplayOnly) {
3720 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003721 }
3722
Robert Carrb89ea9d2018-12-10 13:01:14 -08003723 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003724 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3725 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003726 if (result != NO_ERROR) {
3727 return result;
3728 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003729 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003730
3731 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733}
3734
Cody Northropbc755282017-03-31 12:00:08 -06003735String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3736{
3737 bool matchFound = true;
3738 uint32_t dupeCounter = 0;
3739
3740 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3741 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3742
Dan Stoza436ccf32018-06-21 12:10:12 -07003743 // Grab the state lock since we're accessing mCurrentState
3744 Mutex::Autolock lock(mStateLock);
3745
Cody Northropbc755282017-03-31 12:00:08 -06003746 // Loop over layers until we're sure there is no matching name
3747 while (matchFound) {
3748 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003749 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003750 if (layer->getName() == uniqueName) {
3751 matchFound = true;
3752 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3753 }
3754 });
3755 }
3756
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003757 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3758 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003759
3760 return uniqueName;
3761}
3762
Marissa Wallfd668622018-05-10 10:21:13 -07003763status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3764 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003765 LayerMetadata metadata, PixelFormat& format,
3766 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003767 sp<IGraphicBufferProducer>* gbp,
3768 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003770 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003771 case PIXEL_FORMAT_TRANSPARENT:
3772 case PIXEL_FORMAT_TRANSLUCENT:
3773 format = PIXEL_FORMAT_RGBA_8888;
3774 break;
3775 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003776 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 break;
3778 }
3779
Evan Roskya1f1e152019-01-24 16:17:46 -08003780 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
3781 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07003782 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003783 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003784 *handle = layer->getHandle();
3785 *gbp = layer->getProducer();
3786 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003788
Marissa Wallfd668622018-05-10 10:21:13 -07003789 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003790 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003791}
3792
Marissa Wall61c58622018-07-18 10:12:20 -07003793status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3794 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003795 LayerMetadata metadata, sp<IBinder>* handle,
3796 sp<Layer>* outLayer) {
3797 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
3798 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07003799 *handle = layer->getHandle();
3800 *outLayer = layer;
3801
3802 return NO_ERROR;
3803}
3804
Evan Roskya1f1e152019-01-24 16:17:46 -08003805status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3806 uint32_t h, uint32_t flags, LayerMetadata metadata,
3807 sp<IBinder>* handle, sp<Layer>* outLayer) {
3808 *outLayer = getFactory().createColorLayer(
3809 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003810 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003811 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003812}
3813
Evan Roskya1f1e152019-01-24 16:17:46 -08003814status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3815 uint32_t w, uint32_t h, uint32_t flags,
3816 LayerMetadata metadata, sp<IBinder>* handle,
3817 sp<Layer>* outLayer) {
3818 *outLayer = getFactory().createContainerLayer(
3819 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003820 *handle = (*outLayer)->getHandle();
3821 return NO_ERROR;
3822}
3823
3824
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003825void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003826 mLayersPendingRemoval.add(layer);
3827 mLayersRemoved = true;
3828 setTransactionFlags(eTransactionNeeded);
3829}
3830
Robert Carr695d5282018-12-18 15:27:58 -08003831void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003832{
Robert Carr2e102c92018-10-23 12:11:15 -07003833 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003834 // If a layer has a parent, we allow it to out-live it's handle
3835 // with the idea that the parent holds a reference and will eventually
3836 // be cleaned up. However no one cleans up the top-level so we do so
3837 // here.
3838 if (layer->getParent() == nullptr) {
3839 mCurrentState.layersSortedByZ.remove(layer);
3840 }
3841 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003842
3843 auto it = mLayersByLocalBinderToken.begin();
3844 while (it != mLayersByLocalBinderToken.end()) {
3845 if (it->second == layer) {
3846 it = mLayersByLocalBinderToken.erase(it);
3847 } else {
3848 it++;
3849 }
3850 }
3851
Robert Carr695d5282018-12-18 15:27:58 -08003852 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003853}
3854
Mathias Agopianb60314a2012-04-10 22:09:54 -07003855// ---------------------------------------------------------------------------
3856
Andy McFadden13a082e2012-08-24 10:16:42 -07003857void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003858 const auto display = getDefaultDisplayDeviceLocked();
3859 if (!display) return;
3860
3861 const sp<IBinder> token = display->getDisplayToken().promote();
3862 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003863
Jesse Hall01e29052013-02-19 16:13:35 -08003864 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003865 Vector<ComposerState> state;
3866 Vector<DisplayState> displays;
3867 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003868 d.what = DisplayState::eDisplayProjectionChanged |
3869 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003870 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003871 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003872 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003873 d.frame.makeInvalid();
3874 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003875 d.width = 0;
3876 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003877 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003878 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003879
Dominik Laskowskie9774092018-12-11 10:04:24 -08003880 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003881
Dominik Laskowski83b88212018-12-11 13:34:06 -08003882 const nsecs_t vsyncPeriod = getVsyncPeriod();
3883 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003884
Brian Andersond0010582017-03-07 13:20:31 -08003885 // Use phase of 0 since phase is not known.
3886 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003887 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003888 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003889}
3890
3891void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003892 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003893 postMessageAsync(
3894 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003895}
3896
Ady Abraham27c70212019-06-11 10:52:26 -07003897void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3898 if (mHWCVsyncState != enabled) {
3899 getHwComposer().setVsyncEnabled(displayId, enabled);
3900 mHWCVsyncState = enabled;
3901 }
3902}
3903
Dominik Laskowskie9774092018-12-11 10:04:24 -08003904void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003905 if (display->isVirtual()) {
3906 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003907 return;
3908 }
3909
Dominik Laskowski075d3172018-05-24 15:50:06 -07003910 const auto displayId = display->getId();
3911 LOG_ALWAYS_FATAL_IF(!displayId);
3912
Dominik Laskowski34157762018-10-31 13:07:19 -07003913 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003914
3915 int currentMode = display->getPowerMode();
3916 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003917 return;
3918 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003920 display->setPowerMode(mode);
3921
Lloyd Pique4dccc412018-01-22 17:21:36 -08003922 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003923 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003924 }
3925
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003926 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003927 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003928 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003929 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003930 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003931 mScheduler->onScreenAcquired(mAppConnectionHandle);
3932 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003935 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003936 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003937 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003938
3939 struct sched_param param = {0};
3940 param.sched_priority = 1;
3941 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3942 ALOGW("Couldn't set SCHED_FIFO on display on");
3943 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003944 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003945 // Turn off the display
3946 struct sched_param param = {0};
3947 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3948 ALOGW("Couldn't set SCHED_OTHER on display off");
3949 }
3950
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003952 mScheduler->disableHardwareVsync(true);
3953 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003954 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955
Ady Abraham27c70212019-06-11 10:52:26 -07003956 // Make sure HWVsync is disabled before turning off the display
3957 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3958
Dominik Laskowski075d3172018-05-24 15:50:06 -07003959 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003960 mVisibleRegionsDirty = true;
3961 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003962 } else if (mode == HWC_POWER_MODE_DOZE ||
3963 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003964 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003965 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003966 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003967 mScheduler->onScreenAcquired(mAppConnectionHandle);
3968 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003969 }
3970 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3971 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003972 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003973 mScheduler->disableHardwareVsync(true);
3974 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003975 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003976 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003977 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003978 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003979 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003980 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003982 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003983 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07003984 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003985 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003986 }
3987
Dominik Laskowski34157762018-10-31 13:07:19 -07003988 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003989}
3990
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003992 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003993 const auto display = getDisplayDevice(displayToken);
3994 if (!display) {
3995 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3996 displayToken.get());
3997 } else if (display->isVirtual()) {
3998 ALOGW("Attempt to set power mode %d for virtual display", mode);
3999 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004000 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004001 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004003}
4004
4005// ---------------------------------------------------------------------------
4006
Dominik Laskowskic2867142019-01-21 11:33:38 -08004007status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4008 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004009 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004010
Mathias Agopianbd115332013-04-18 16:41:04 -07004011 IPCThreadState* ipc = IPCThreadState::self();
4012 const int pid = ipc->getCallingPid();
4013 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004014
Mathias Agopianbd115332013-04-18 16:41:04 -07004015 if ((uid != AID_SHELL) &&
4016 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004017 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4018 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004020 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004021 // (this would indicate SF is stuck, but we want to be able to
4022 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004023 status_t err = mStateLock.timedLock(s2ns(1));
4024 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004025 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004026 StringAppendF(&result,
4027 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4028 "(no locks held)\n",
4029 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004030 }
4031
Dominik Laskowskic2867142019-01-21 11:33:38 -08004032 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004033
Dominik Laskowskic2867142019-01-21 11:33:38 -08004034 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004035 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004036 {"--dispsync"s,
4037 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004038 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4039 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4040 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4041 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4042 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4043 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004044 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004045 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4046 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047
Dominik Laskowskic2867142019-01-21 11:33:38 -08004048 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049
Dominik Laskowski46470112019-08-02 13:13:11 -07004050 const auto it = dumpers.find(flag);
4051 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004052 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004053 } else if (!asProto) {
4054 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004055 }
4056
Mathias Agopian9795c422009-08-26 16:36:26 -07004057 if (locked) {
4058 mStateLock.unlock();
4059 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004060
Dominik Laskowski46470112019-08-02 13:13:11 -07004061 if (it == dumpers.end()) {
4062 const LayersProto layersProto = dumpProtoFromMainThread();
4063 if (asProto) {
4064 result.append(layersProto.SerializeAsString());
4065 } else {
4066 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4067 result.append(LayerProtoParser::layerTreeToString(layerTree));
4068 result.append("\n");
4069 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004072 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 return NO_ERROR;
4074}
4075
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004076status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4077 if (asProto && mTracing.isEnabled()) {
4078 mTracing.writeToFileAsync();
4079 }
4080
4081 return doDump(fd, DumpArgs(), asProto);
4082}
4083
Dominik Laskowskic2867142019-01-21 11:33:38 -08004084void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004085 mCurrentState.traverseInZOrder(
4086 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004087}
4088
Dominik Laskowskic2867142019-01-21 11:33:38 -08004089void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004090 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004091
Dominik Laskowskic2867142019-01-21 11:33:38 -08004092 if (args.size() > 1) {
4093 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004094 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004095 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004096 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004097 }
Robert Carr2047fae2016-11-28 14:09:09 -08004098 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004099 } else {
4100 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004101 }
4102}
4103
Dominik Laskowskic2867142019-01-21 11:33:38 -08004104void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004105 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004106 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004107 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004108 }
Robert Carr2047fae2016-11-28 14:09:09 -08004109 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004110
Svetoslavd85084b2014-03-20 10:28:31 -07004111 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004112}
4113
Dominik Laskowskic2867142019-01-21 11:33:38 -08004114void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4115 mTimeStats->parseArgs(asProto, args, result);
4116}
4117
Jamie Gennis6547ff42013-07-16 20:12:42 -07004118// This should only be called from the main thread. Otherwise it would need
4119// the lock and should use mCurrentState rather than mDrawingState.
4120void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004121 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004122 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004123 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004124
4125 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4126}
4127
Yiwei Zhang5434a782018-12-05 18:06:32 -08004128void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004129 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004130
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004131 if (isLayerTripleBufferingDisabled())
4132 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004133
Yiwei Zhang5434a782018-12-05 18:06:32 -08004134 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4135 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4136 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4137 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4138 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4139 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004140 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004141}
4142
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004143void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004144 mScheduler->dump(result);
4145 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
4146
4147 mRefreshRateStats.dump(result);
4148 result.append("\n");
4149
Ana Krulec757f63a2019-01-25 10:46:18 -08004150 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004151 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004152 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004153 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004154
Ady Abraham42b3beb2019-07-09 18:09:52 -07004155 StringAppendF(&result, "Allowed Display Configs: ");
Dominik Laskowski98041832019-08-01 18:35:59 -07004156 for (const auto& [type, rate] : mRefreshRateConfigs.getRefreshRates()) {
4157 if (rate && isDisplayConfigAllowed(rate->configId)) {
4158 StringAppendF(&result, "%" PRIu32 " Hz, ", rate->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004159 }
4160 }
4161 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4162 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004163
Ana Krulecc2870422019-01-29 19:00:58 -08004164 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004165}
4166
Yiwei Zhang5434a782018-12-05 18:06:32 -08004167void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4168 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004169 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4170 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004171 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004172 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004173 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004174 }
David Sodman4a36e932017-11-07 14:29:47 -08004175 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004176 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004177 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004178 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4179 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004180}
4181
Dan Stozae77c7662016-05-13 11:37:28 -07004182void SurfaceFlinger::recordBufferingStats(const char* layerName,
4183 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004184 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4185 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004186 for (const auto& segment : history) {
4187 if (!segment.usedThirdBuffer) {
4188 stats.twoBufferTime += segment.totalTime;
4189 }
4190 if (segment.occupancyAverage < 1.0f) {
4191 stats.doubleBufferedTime += segment.totalTime;
4192 } else if (segment.occupancyAverage < 2.0f) {
4193 stats.tripleBufferedTime += segment.totalTime;
4194 }
4195 ++stats.numSegments;
4196 stats.totalTime += segment.totalTime;
4197 }
4198}
4199
Yiwei Zhang5434a782018-12-05 18:06:32 -08004200void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4201 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004202
4203 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4204 const size_t count = currentLayers.size();
4205 for (size_t i=0 ; i<count ; i++) {
4206 currentLayers[i]->dumpFrameEvents(result);
4207 }
4208}
4209
Yiwei Zhang5434a782018-12-05 18:06:32 -08004210void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004211 result.append("Buffering stats:\n");
4212 result.append(" [Layer name] <Active time> <Two buffer> "
4213 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004214 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004215 typedef std::tuple<std::string, float, float, float> BufferTuple;
4216 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004217 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004218 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004219 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004220 if (stats.numSegments == 0) {
4221 continue;
4222 }
4223 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4224 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4225 stats.totalTime;
4226 float doubleBufferRatio = static_cast<float>(
4227 stats.doubleBufferedTime) / stats.totalTime;
4228 float tripleBufferRatio = static_cast<float>(
4229 stats.tripleBufferedTime) / stats.totalTime;
4230 sorted.insert({activeTime, {name, twoBufferRatio,
4231 doubleBufferRatio, tripleBufferRatio}});
4232 }
4233 for (const auto& sortedPair : sorted) {
4234 float activeTime = sortedPair.first;
4235 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4237 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004238 }
4239 result.append("\n");
4240}
4241
Yiwei Zhang5434a782018-12-05 18:06:32 -08004242void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004243 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004244 const auto displayId = display->getId();
4245 if (!displayId) {
4246 continue;
4247 }
4248 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004249 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004250 continue;
4251 }
4252
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result,
4254 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4255 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004256 uint8_t port;
4257 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004258 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004259 result.append("no identification data\n");
4260 continue;
4261 }
4262
4263 if (!isEdid(data)) {
4264 result.append("unknown identification data: ");
4265 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004267 }
4268 result.append("\n");
4269 continue;
4270 }
4271
4272 const auto edid = parseEdid(data);
4273 if (!edid) {
4274 result.append("invalid EDID: ");
4275 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004276 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004277 }
4278 result.append("\n");
4279 continue;
4280 }
4281
Yiwei Zhang5434a782018-12-05 18:06:32 -08004282 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004283 result.append(edid->displayName.data(), edid->displayName.length());
4284 result.append("\"\n");
4285 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004286}
4287
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004289 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004290 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4291 StringAppendF(&result, "DisplayColorSetting: %s\n",
4292 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004293
4294 // TODO: print out if wide-color mode is active or not
4295
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004296 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297 const auto displayId = display->getId();
4298 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004299 continue;
4300 }
4301
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004304 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004306 }
4307
Lloyd Pique32cbe282018-10-19 13:09:22 -07004308 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309 StringAppendF(&result, " Current color mode: %s (%d)\n",
4310 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004311 }
4312 result.append("\n");
4313}
4314
Vishnu Nair8406fd72019-07-30 11:29:31 -07004315LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004316 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004317 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004318 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004319 layer->writeToProtoDrawingState(layerProto, traceFlags);
4320 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004321 });
4322
4323 return layersProto;
4324}
4325
Vishnu Nair8406fd72019-07-30 11:29:31 -07004326LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4327 LayersProto layersProto;
4328 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4329 return layersProto;
4330}
4331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4333 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004334 Colorizer colorizer(colorize);
4335
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336 // figure out if we're stuck somewhere
4337 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004339 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4340
4341 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004342 * Dump library configuration.
4343 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004344
4345 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004346 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004347 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004348 appendSfConfigString(result);
4349 appendUiConfigString(result);
4350 appendGuiConfigString(result);
4351 result.append("\n");
4352
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004353 result.append("\nDisplay identification data:\n");
4354 dumpDisplayIdentificationData(result);
4355
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004356 result.append("\nWide-Color information:\n");
4357 dumpWideColorInfo(result);
4358
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004359 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004360 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004362 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004363 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004364
Andy McFadden41d67d72014-04-25 16:58:34 -07004365 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004366 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004367 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004368 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004369 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004370
Dan Stozab90cf072015-03-05 11:05:59 -08004371 dumpStaticScreenStats(result);
4372 result.append("\n");
4373
Alec Mouri40189b02019-03-05 15:07:54 -08004374 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4375 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4376 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004377
Dan Stozae77c7662016-05-13 11:37:28 -07004378 dumpBufferingStats(result);
4379
Andy McFadden4803b742012-09-24 19:07:20 -07004380 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381 * Dump the visible layer list
4382 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004383 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004384 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4386 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004387 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004388
Chia-I Wu2f884132018-09-13 15:17:58 -07004389 {
Lloyd Pique207def92019-02-28 16:09:52 -08004390 StringAppendF(&result, "Composition layers\n");
4391 mDrawingState.traverseInZOrder([&](Layer* layer) {
4392 auto compositionLayer = layer->getCompositionLayer();
4393 if (compositionLayer) compositionLayer->dump(result);
4394 });
4395 }
4396
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004398 * Dump Display state
4399 */
4400
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004401 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004403 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004404 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004405 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004406 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004407 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004408
4409 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410 * Dump SurfaceFlinger global state
4411 */
4412
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004414 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004415 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004416
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004417 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004419 DebugEGLImageTracker::getInstance()->dump(result);
4420
Dominik Laskowski075d3172018-05-24 15:50:06 -07004421 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004422 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4423 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4425 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004426 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result,
4428 " transaction-flags : %08x\n"
4429 " gpu_to_cpu_unsupported : %d\n",
4430 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004431
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004432 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004433 displayId && getHwComposer().isConnected(*displayId)) {
4434 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 StringAppendF(&result,
4436 " refresh-rate : %f fps\n"
4437 " x-dpi : %f\n"
4438 " y-dpi : %f\n",
4439 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4440 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004441 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444
Dan Stozae22aec72016-08-01 13:20:59 -07004445 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004446 * Tracing state
4447 */
4448 mTracing.dump(result);
4449 result.append("\n");
4450
4451 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004452 * HWC layer minidump
4453 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004454 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004455 const auto displayId = display->getId();
4456 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004457 continue;
4458 }
4459
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004461 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004462 const sp<DisplayDevice> displayDevice = display;
4463 mCurrentState.traverseInZOrder(
4464 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004465 result.append("\n");
4466 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467
4468 /*
4469 * Dump HWComposer state
4470 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004471 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004472 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004473 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004474 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004476 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477
4478 /*
4479 * Dump gralloc state
4480 */
4481 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4482 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004483
4484 /*
4485 * Dump VrFlinger state if in use.
4486 */
4487 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4488 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004490 result.append("\n");
4491 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004492
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004493 result.append(mTimeStats->miniDump());
4494 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495}
4496
Chia-I Wu28f320b2018-05-03 11:02:56 -07004497void SurfaceFlinger::updateColorMatrixLocked() {
4498 mat4 colorMatrix;
4499 if (mGlobalSaturationFactor != 1.0f) {
4500 // Rec.709 luma coefficients
4501 float3 luminance{0.213f, 0.715f, 0.072f};
4502 luminance *= 1.0f - mGlobalSaturationFactor;
4503 mat4 saturationMatrix = mat4(
4504 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4505 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4506 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4507 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4508 );
4509 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4510 } else {
4511 colorMatrix = mClientColorMatrix * mDaltonizer();
4512 }
4513
4514 if (mCurrentState.colorMatrix != colorMatrix) {
4515 mCurrentState.colorMatrix = colorMatrix;
4516 mCurrentState.colorMatrixChanged = true;
4517 setTransactionFlags(eTransactionNeeded);
4518 }
4519}
4520
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004521status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004522#pragma clang diagnostic push
4523#pragma clang diagnostic error "-Wswitch-enum"
4524 switch (static_cast<ISurfaceComposerTag>(code)) {
4525 // These methods should at minimum make sure that the client requested
4526 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004527 case BOOT_FINISHED:
4528 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004529 case CREATE_DISPLAY:
4530 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004531 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004532 case GET_ANIMATION_FRAME_STATS:
4533 case GET_HDR_CAPABILITIES:
4534 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004535 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004536 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004537 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004538 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004539 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004540 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004541 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004542 case GET_DISPLAYED_CONTENT_SAMPLE:
4543 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004544 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4545 IPCThreadState* ipc = IPCThreadState::self();
4546 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4547 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004548 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549 }
Robert Carr1db73f62016-12-21 12:58:51 -08004550 return OK;
4551 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004552 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004553 IPCThreadState* ipc = IPCThreadState::self();
4554 const int pid = ipc->getCallingPid();
4555 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004556 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4557 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004558 return PERMISSION_DENIED;
4559 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004560 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004561 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 // Used by apps to hook Choreographer to SurfaceFlinger.
4563 case CREATE_DISPLAY_EVENT_CONNECTION:
4564 // The following calls are currently used by clients that do not
4565 // request necessary permissions. However, they do not expose any secret
4566 // information, so it is OK to pass them.
4567 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004568 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004569 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004570 case GET_PHYSICAL_DISPLAY_IDS:
4571 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004572 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004573 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004574 case GET_DISPLAY_CONFIGS:
4575 case GET_DISPLAY_STATS:
4576 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4577 // Calling setTransactionState is safe, because you need to have been
4578 // granted a reference to Client* and Handle* to do anything with it.
4579 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004580 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004581 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004582 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004583 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004584 case IS_WIDE_COLOR_DISPLAY:
4585 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4586 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004587 return OK;
4588 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004589 case CAPTURE_LAYERS: {
4590 IPCThreadState* ipc = IPCThreadState::self();
4591 const int pid = ipc->getCallingPid();
4592 const int uid = ipc->getCallingUid();
4593 // allow media to capture layer for video thumbnails
4594 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4595 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4596 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4597 return PERMISSION_DENIED;
4598 }
4599 return OK;
4600 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004601 case CAPTURE_SCREEN:
4602 case ADD_REGION_SAMPLING_LISTENER:
4603 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004604 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004605 IPCThreadState* ipc = IPCThreadState::self();
4606 const int pid = ipc->getCallingPid();
4607 const int uid = ipc->getCallingUid();
4608 if ((uid != AID_GRAPHICS) &&
4609 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4610 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4611 return PERMISSION_DENIED;
4612 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004613 return OK;
4614 }
4615 // The following codes are deprecated and should never be allowed to access SF.
4616 case CONNECT_DISPLAY_UNUSED:
4617 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4618 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4619 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004620 }
chaviw93df2ea2019-04-30 16:45:12 -07004621 case CAPTURE_SCREEN_BY_ID: {
4622 IPCThreadState* ipc = IPCThreadState::self();
4623 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004624 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004625 return OK;
4626 }
4627 return PERMISSION_DENIED;
4628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004630
4631 // These codes are used for the IBinder protocol to either interrogate the recipient
4632 // side of the transaction for its canonical interface descriptor or to dump its state.
4633 // We let them pass by default.
4634 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4635 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4636 code == IBinder::SYSPROPS_TRANSACTION) {
4637 return OK;
4638 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004639 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004640 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004641 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004642 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4643 return OK;
4644 }
4645 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4646 return PERMISSION_DENIED;
4647#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004648}
4649
Ana Krulec13be8ad2018-08-21 02:43:56 +00004650status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4651 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004652 status_t credentialCheck = CheckTransactCodeCredentials(code);
4653 if (credentialCheck != OK) {
4654 return credentialCheck;
4655 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4658 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004659 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004660 IPCThreadState* ipc = IPCThreadState::self();
4661 const int uid = ipc->getCallingUid();
4662 if (CC_UNLIKELY(uid != AID_SYSTEM
4663 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004664 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004665 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004666 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004667 return PERMISSION_DENIED;
4668 }
4669 int n;
4670 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004671 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004672 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004673 return NO_ERROR;
4674 case 1002: // SHOW_UPDATES
4675 n = data.readInt32();
4676 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004677 invalidateHwcGeometry();
4678 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004681 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004682 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004684 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004685 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004686 setTransactionFlags(
4687 eTransactionNeeded|
4688 eDisplayTransactionNeeded|
4689 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004690 return NO_ERROR;
4691 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004692 case 1006:{ // send empty update
4693 signalRefresh();
4694 return NO_ERROR;
4695 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004696 case 1008: // toggle use of hw composer
4697 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004698 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004699 invalidateHwcGeometry();
4700 repaintEverything();
4701 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004702 case 1009: // toggle use of transform hint
4703 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004704 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004705 invalidateHwcGeometry();
4706 repaintEverything();
4707 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004708 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004709 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 reply->writeInt32(0);
4711 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004712 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004713 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 return NO_ERROR;
4715 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004716 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004717 if (!display) {
4718 return NAME_NOT_FOUND;
4719 }
4720
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004721 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004722 return NO_ERROR;
4723 }
4724 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004725 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004726 // daltonize
4727 n = data.readInt32();
4728 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004729 case 1:
4730 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4731 break;
4732 case 2:
4733 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4734 break;
4735 case 3:
4736 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4737 break;
4738 default:
4739 mDaltonizer.setType(ColorBlindnessType::None);
4740 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004741 }
4742 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004743 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004744 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004745 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004746 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004747
4748 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004749 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004750 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004751 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004752 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 // apply a color matrix
4754 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004755 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004756 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004757 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004758 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004759 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004760 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004761 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004762 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004763 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004764 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004765
4766 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4767 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004769 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4770 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4771 }
4772
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004774 return NO_ERROR;
4775 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004776 case 1016: { // Unused.
4777 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004778 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004779 case 1017: {
4780 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004781 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004782 return NO_ERROR;
4783 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004784 case 1018: { // Modify Choreographer's phase offset
4785 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004786 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004787 return NO_ERROR;
4788 }
4789 case 1019: { // Modify SurfaceFlinger's phase offset
4790 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004791 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004792 return NO_ERROR;
4793 }
Irvel468051e2016-06-13 16:44:44 -07004794 case 1020: { // Layer updates interceptor
4795 n = data.readInt32();
4796 if (n) {
4797 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004798 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004799 }
4800 else{
4801 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004802 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004803 }
4804 return NO_ERROR;
4805 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004806 case 1021: { // Disable HWC virtual displays
4807 n = data.readInt32();
4808 mUseHwcVirtualDisplays = !n;
4809 return NO_ERROR;
4810 }
Romain Guy0147a172017-06-01 13:53:56 -07004811 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004812 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004813 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004814
Chia-I Wu28f320b2018-05-03 11:02:56 -07004815 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004816 return NO_ERROR;
4817 }
Romain Guy54f154a2017-10-24 21:40:32 +01004818 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004819 int32_t colorMode;
4820
Chia-I Wu0d711262018-05-21 15:19:35 -07004821 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004822 if (data.readInt32(&colorMode) == NO_ERROR) {
4823 mForceColorMode = static_cast<ColorMode>(colorMode);
4824 }
Romain Guy54f154a2017-10-24 21:40:32 +01004825 invalidateHwcGeometry();
4826 repaintEverything();
4827 return NO_ERROR;
4828 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004829 // Deprecate, use 1030 to check whether the device is color managed.
4830 case 1024: {
4831 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004832 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004833 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004834 n = data.readInt32();
4835 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004836 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004837 Mutex::Autolock lock(mStateLock);
4838 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004839 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004840 reply->writeInt32(NO_ERROR);
4841 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004842 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004843 bool writeFile = false;
4844 {
4845 Mutex::Autolock lock(mStateLock);
4846 mTracingEnabledChanged = true;
4847 writeFile = mTracing.disable();
4848 }
4849
4850 if (writeFile) {
4851 reply->writeInt32(mTracing.writeToFile());
4852 } else {
4853 reply->writeInt32(NO_ERROR);
4854 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004855 }
4856 return NO_ERROR;
4857 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004858 case 1026: { // Get layer tracing status
4859 reply->writeBool(mTracing.isEnabled());
4860 return NO_ERROR;
4861 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004862 // Is a DisplayColorSetting supported?
4863 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004864 const auto display = getDefaultDisplayDevice();
4865 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004866 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004867 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004868
4869 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4870 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004871 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004872 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004873 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004874 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004875 reply->writeBool(true);
4876 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004877 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004878 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004879 break;
4880 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004881 reply->writeBool(
4882 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004883 break;
4884 }
4885 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004886 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004887 // Is VrFlinger active?
4888 case 1028: {
4889 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004890 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004891 return NO_ERROR;
4892 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004893 // Set buffer size for SF tracing (value in KB)
4894 case 1029: {
4895 n = data.readInt32();
4896 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4897 ALOGW("Invalid buffer size: %d KB", n);
4898 reply->writeInt32(BAD_VALUE);
4899 return BAD_VALUE;
4900 }
4901
4902 ALOGD("Updating trace buffer to %d KB", n);
4903 mTracing.setBufferSize(n * 1024);
4904 reply->writeInt32(NO_ERROR);
4905 return NO_ERROR;
4906 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004907 // Is device color managed?
4908 case 1030: {
4909 reply->writeBool(useColorManagement);
4910 return NO_ERROR;
4911 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004912 // Override default composition data space
4913 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4914 // && adb shell stop zygote && adb shell start zygote
4915 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4916 // adb shell stop zygote && adb shell start zygote
4917 case 1031: {
4918 Mutex::Autolock _l(mStateLock);
4919 n = data.readInt32();
4920 if (n) {
4921 n = data.readInt32();
4922 if (n) {
4923 Dataspace dataspace = static_cast<Dataspace>(n);
4924 if (!validateCompositionDataspace(dataspace)) {
4925 return BAD_VALUE;
4926 }
4927 mDefaultCompositionDataspace = dataspace;
4928 }
4929 n = data.readInt32();
4930 if (n) {
4931 Dataspace dataspace = static_cast<Dataspace>(n);
4932 if (!validateCompositionDataspace(dataspace)) {
4933 return BAD_VALUE;
4934 }
4935 mWideColorGamutCompositionDataspace = dataspace;
4936 }
4937 } else {
4938 // restore composition data space.
4939 mDefaultCompositionDataspace = defaultCompositionDataspace;
4940 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4941 }
4942 return NO_ERROR;
4943 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004944 // Set trace flags
4945 case 1033: {
4946 n = data.readUint32();
4947 ALOGD("Updating trace flags to 0x%x", n);
4948 mTracing.setTraceFlags(n);
4949 reply->writeInt32(NO_ERROR);
4950 return NO_ERROR;
4951 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004952 case 1034: {
4953 // TODO(b/129297325): expose this via developer menu option
4954 n = data.readInt32();
4955 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004956 RefreshRateType type;
4957 {
4958 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4959 type = mDesiredActiveConfig.type;
4960 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004961 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004962 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004963 } else if (!n) {
4964 mRefreshRateOverlay.reset();
4965 }
4966 return NO_ERROR;
4967 }
Ady Abraham34392f72019-04-10 11:29:27 -07004968 case 1035: {
4969 n = data.readInt32();
4970 mDebugDisplayConfigSetByBackdoor = false;
4971 if (n >= 0) {
4972 const auto displayToken = getInternalDisplayToken();
4973 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4974 if (result != NO_ERROR) {
4975 return result;
4976 }
4977 mDebugDisplayConfigSetByBackdoor = true;
4978 }
4979 return NO_ERROR;
4980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 }
4982 }
4983 return err;
4984}
4985
Steven Thomas6d8110b2017-08-31 18:24:21 -07004986void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004987 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004988 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004989}
4990
Ana Krulec7d1d6832018-12-27 11:10:09 -08004991void SurfaceFlinger::repaintEverythingForHWC() {
4992 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004993 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004994}
4995
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004996// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4997class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004998public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004999 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5000 ~WindowDisconnector() {
5001 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005002 }
5003
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005004private:
5005 ANativeWindow* mWindow;
5006 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005007};
5008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005009status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005010 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5011 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005012 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005013 uint32_t reqWidth, uint32_t reqHeight,
5014 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005015 ISurfaceComposer::Rotation rotation,
5016 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005017 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005019 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005020
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005021 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5022
Chia-I Wu20261cb2018-08-23 12:55:44 -07005023 sp<DisplayDevice> display;
5024 {
5025 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005026
Chia-I Wu20261cb2018-08-23 12:55:44 -07005027 display = getDisplayDeviceLocked(displayToken);
5028 if (!display) return BAD_VALUE;
5029
Chia-I Wucb023152018-08-28 12:57:23 -07005030 // set the requested width/height to the logical display viewport size
5031 // by default
5032 if (reqWidth == 0 || reqHeight == 0) {
5033 reqWidth = uint32_t(display->getViewport().width());
5034 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005035 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005036 }
5037
Peiyong Lin0e003c92018-09-17 11:09:51 -07005038 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005039 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005040
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005041 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5042 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005043 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005044 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005045}
5046
chaviw93df2ea2019-04-30 16:45:12 -07005047static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5048 switch (colorMode) {
5049 case ColorMode::DISPLAY_P3:
5050 case ColorMode::BT2100_PQ:
5051 case ColorMode::BT2100_HLG:
5052 case ColorMode::DISPLAY_BT2020:
5053 return Dataspace::DISPLAY_P3;
5054 default:
5055 return Dataspace::V0_SRGB;
5056 }
5057}
5058
5059const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5060 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5061 if (displayToken) {
5062 return getDisplayDeviceLocked(displayToken);
5063 }
5064 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5065 // may not have a displayId.
5066 for (const auto& [token, display] : mDisplays) {
5067 if (display->getLayerStack() == displayOrLayerStack) {
5068 return display;
5069 }
5070 }
5071 return nullptr;
5072}
5073
5074status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5075 sp<GraphicBuffer>* outBuffer) {
5076 sp<DisplayDevice> display;
5077 uint32_t width;
5078 uint32_t height;
5079 ui::Transform::orientation_flags captureOrientation;
5080 {
5081 Mutex::Autolock _l(mStateLock);
5082 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5083 if (!display) {
5084 return BAD_VALUE;
5085 }
5086
5087 width = uint32_t(display->getViewport().width());
5088 height = uint32_t(display->getViewport().height());
5089
5090 captureOrientation = fromSurfaceComposerRotation(
5091 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005092 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5093 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5094 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5095 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5096 }
chaviw93df2ea2019-04-30 16:45:12 -07005097 *outDataspace =
5098 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5099 }
5100
5101 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5102 false /* captureSecureLayers */);
5103
5104 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5105 std::placeholders::_1);
5106 bool ignored = false;
5107 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5108 false /* useIdentityTransform */,
5109 ignored /* outCapturedSecureLayers */);
5110}
5111
Robert Carr866455f2019-04-02 16:28:26 -07005112status_t SurfaceFlinger::captureLayers(
5113 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5114 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5115 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5116 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005117 ATRACE_CALL();
5118
5119 class LayerRenderArea : public RenderArea {
5120 public:
Robert Carr578038f2018-03-09 12:25:24 -08005121 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005122 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5123 bool childrenOnly)
5124 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005125 mLayer(layer),
5126 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005127 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005128 mFlinger(flinger),
5129 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005130 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005131 Rect getBounds() const override {
5132 const Layer::State& layerState(mLayer->getDrawingState());
5133 return mLayer->getBufferSize(layerState);
5134 }
Marissa Wall61c58622018-07-18 10:12:20 -07005135 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005136 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005137 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005138 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005139 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005140 }
chaviwa76b2712017-09-20 12:02:26 -07005141 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005142 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005143 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005144 Rect getSourceCrop() const override {
5145 if (mCrop.isEmpty()) {
5146 return getBounds();
5147 } else {
5148 return mCrop;
5149 }
5150 }
Robert Carr578038f2018-03-09 12:25:24 -08005151 class ReparentForDrawing {
5152 public:
5153 const sp<Layer>& oldParent;
5154 const sp<Layer>& newParent;
5155
Vishnu Nair4351ad52019-02-11 14:13:02 -08005156 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5157 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005158 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005159 // Compute and cache the bounds for the new parent layer.
5160 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005161 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005162 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005163 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005164 };
5165
5166 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005167 const Rect sourceCrop = getSourceCrop();
5168 // no need to check rotation because there is none
5169 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5170 sourceCrop.height() != getReqHeight();
5171
Robert Carr578038f2018-03-09 12:25:24 -08005172 if (!mChildrenOnly) {
5173 mTransform = mLayer->getTransform().inverse();
5174 drawLayers();
5175 } else {
5176 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005177 // In the "childrenOnly" case we reparent the children to a screenshot
5178 // layer which has no properties set and which does not draw.
5179 sp<ContainerLayer> screenshotParentLayer =
5180 mFlinger->getFactory().createContainerLayer(
5181 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5182 bounds.getWidth(), bounds.getHeight(), 0,
5183 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005184
Vishnu Nair4351ad52019-02-11 14:13:02 -08005185 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005186 drawLayers();
5187 }
5188 }
chaviwa76b2712017-09-20 12:02:26 -07005189
chaviwa76b2712017-09-20 12:02:26 -07005190 private:
chaviw7206d492017-11-10 16:16:12 -08005191 const sp<Layer> mLayer;
5192 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005193
Peiyong Linefefaac2018-08-17 12:27:51 -07005194 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005195 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005196
5197 SurfaceFlinger* mFlinger;
5198 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005199 };
5200
Robert Carrc0df3122019-04-11 13:18:21 -07005201 int reqWidth = 0;
5202 int reqHeight = 0;
5203 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005204 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005205 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005206
Robert Carrc0df3122019-04-11 13:18:21 -07005207 {
5208 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005209
Robert Carrc0df3122019-04-11 13:18:21 -07005210 parent = fromHandle(layerHandleBinder);
5211 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5212 ALOGE("captureLayers called with an invalid or removed parent");
5213 return NAME_NOT_FOUND;
5214 }
5215
5216 const int uid = IPCThreadState::self()->getCallingUid();
5217 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5218 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5219 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5220 return PERMISSION_DENIED;
5221 }
5222
5223 if (sourceCrop.width() <= 0) {
5224 crop.left = 0;
5225 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5226 }
5227
5228 if (sourceCrop.height() <= 0) {
5229 crop.top = 0;
5230 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5231 }
5232 reqWidth = crop.width() * frameScale;
5233 reqHeight = crop.height() * frameScale;
5234
5235 for (const auto& handle : excludeHandles) {
5236 sp<Layer> excludeLayer = fromHandle(handle);
5237 if (excludeLayer != nullptr) {
5238 excludeLayers.emplace(excludeLayer);
5239 } else {
5240 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5241 return NAME_NOT_FOUND;
5242 }
5243 }
5244 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005245
Chia-I Wu20261cb2018-08-23 12:55:44 -07005246 // really small crop or frameScale
5247 if (reqWidth <= 0) {
5248 reqWidth = 1;
5249 }
5250 if (reqHeight <= 0) {
5251 reqHeight = 1;
5252 }
5253
Robert Carr866455f2019-04-02 16:28:26 -07005254 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5255 auto traverseLayers = [parent, childrenOnly,
5256 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005257 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5258 if (!layer->isVisible()) {
5259 return;
Robert Carr578038f2018-03-09 12:25:24 -08005260 } else if (childrenOnly && layer == parent.get()) {
5261 return;
chaviwa76b2712017-09-20 12:02:26 -07005262 }
Robert Carr866455f2019-04-02 16:28:26 -07005263
5264 sp<Layer> p = layer;
5265 while (p != nullptr) {
5266 if (excludeLayers.count(p) != 0) {
5267 return;
5268 }
5269 p = p->getParent();
5270 }
5271
chaviwa76b2712017-09-20 12:02:26 -07005272 visitor(layer);
5273 });
5274 };
Robert Carr108b2c72019-04-02 16:32:58 -07005275
5276 bool outCapturedSecureLayers = false;
5277 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5278 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005279}
5280
5281status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5282 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005283 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005284 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005285 bool useIdentityTransform,
5286 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005287 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005288
Peiyong Lin0e003c92018-09-17 11:09:51 -07005289 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005290 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5291 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005292 *outBuffer =
5293 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5294 static_cast<android_pixel_format>(reqPixelFormat), 1,
5295 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005296
Robert Carr108b2c72019-04-02 16:32:58 -07005297 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5298 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005299}
5300
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005301status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5302 TraverseLayersFunction traverseLayers,
5303 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005304 bool useIdentityTransform,
5305 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005306 // This mutex protects syncFd and captureResult for communication of the return values from the
5307 // main thread back to this Binder thread
5308 std::mutex captureMutex;
5309 std::condition_variable captureCondition;
5310 std::unique_lock<std::mutex> captureLock(captureMutex);
5311 int syncFd = -1;
5312 std::optional<status_t> captureResult;
5313
Robert Carr03480e22018-01-04 16:02:06 -08005314 const int uid = IPCThreadState::self()->getCallingUid();
5315 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5316
Dominik Laskowski8c001672018-05-30 16:52:06 -07005317 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 // If there is a refresh pending, bug out early and tell the binder thread to try again
5319 // after the refresh.
5320 if (mRefreshPending) {
5321 ATRACE_NAME("Skipping screenshot for now");
5322 std::unique_lock<std::mutex> captureLock(captureMutex);
5323 captureResult = std::make_optional<status_t>(EAGAIN);
5324 captureCondition.notify_one();
5325 return;
5326 }
5327
5328 status_t result = NO_ERROR;
5329 int fd = -1;
5330 {
5331 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005332 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005333 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005334 useIdentityTransform, forSystem, &fd,
5335 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005336 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005337 }
5338
5339 {
5340 std::unique_lock<std::mutex> captureLock(captureMutex);
5341 syncFd = fd;
5342 captureResult = std::make_optional<status_t>(result);
5343 captureCondition.notify_one();
5344 }
5345 });
5346
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005347 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005348 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005349 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005350 while (*captureResult == EAGAIN) {
5351 captureResult.reset();
5352 result = postMessageAsync(message);
5353 if (result != NO_ERROR) {
5354 return result;
5355 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005356 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 }
5358 result = *captureResult;
5359 }
5360
5361 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005362 sync_wait(syncFd, -1);
5363 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005365
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005367}
5368
chaviwa76b2712017-09-20 12:02:26 -07005369void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005370 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005371 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5372 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005373 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005374
chaviwa76b2712017-09-20 12:02:26 -07005375 const auto reqWidth = renderArea.getReqWidth();
5376 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005377 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005378 const auto transform = renderArea.getTransform();
5379 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005380
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005381 renderengine::DisplaySettings clientCompositionDisplay;
5382 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005383
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005384 // assume that bounds are never offset, and that they are the same as the
5385 // buffer bounds.
5386 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005387 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005388 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005389
5390 // Now take into account the rotation flag. We append a transform that
5391 // rotates the layer stack about the origin, then translate by buffer
5392 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005393 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005394 int displacementX = 0;
5395 int displacementY = 0;
5396 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5397 switch (rotation) {
5398 case ui::Transform::ROT_90:
5399 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005400 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005401 break;
5402 case ui::Transform::ROT_180:
5403 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005404 displacementY = renderArea.getBounds().getWidth();
5405 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005406 break;
5407 case ui::Transform::ROT_270:
5408 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005409 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005410 break;
5411 default:
5412 break;
5413 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005414
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005415 // We need to transform the clipping window into the right spot.
5416 // First, rotate the clipping rectangle by the rotation hint to get the
5417 // right orientation
5418 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5419 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5420 const vec4 rotClipTL = rotMatrix * clipTL;
5421 const vec4 rotClipBR = rotMatrix * clipBR;
5422 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5423 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5424 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5425 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5426
5427 // Now reposition the clipping rectangle with the displacement vector
5428 // computed above.
5429 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005430 clientCompositionDisplay.clip =
5431 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5432 newClipRight + displacementX, newClipBottom + displacementY);
5433
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005434 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005435 clientCompositionDisplay.globalTransform =
5436 clipTransform * clientCompositionDisplay.globalTransform;
5437
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005438 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5439 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005440
chaviw50da5042018-04-09 13:49:37 -07005441 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005442
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005443 renderengine::LayerSettings fillLayer;
5444 fillLayer.source.buffer.buffer = nullptr;
5445 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5446 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5447 fillLayer.alpha = half(alpha);
5448 clientCompositionLayers.push_back(fillLayer);
5449
5450 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005451 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005452 const bool supportProtectedContent = false;
5453 Region clip(renderArea.getBounds());
5454 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5455 clip,
5456 useIdentityTransform,
5457 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5458 renderArea.isSecure(),
5459 supportProtectedContent,
5460 clearRegion,
5461 };
5462 auto result = layer->prepareClientComposition(targetSettings);
5463 if (result) {
5464 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005465 }
chaviwa76b2712017-09-20 12:02:26 -07005466 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005467
5468 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005469 // Use an empty fence for the buffer fence, since we just created the buffer so
5470 // there is no need for synchronization with the GPU.
5471 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005472 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005473 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005474 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005475 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005476
5477 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005478}
5479
chaviwa76b2712017-09-20 12:02:26 -07005480status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5481 TraverseLayersFunction traverseLayers,
5482 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005483 bool useIdentityTransform, bool forSystem,
5484 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005485 ATRACE_CALL();
5486
chaviwa76b2712017-09-20 12:02:26 -07005487 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005488 outCapturedSecureLayers =
5489 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005490 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005491
Robert Carr03480e22018-01-04 16:02:06 -08005492 // We allow the system server to take screenshots of secure layers for
5493 // use in situations like the Screen-rotation animation and place
5494 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005495 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005496 ALOGW("FB is protected: PERMISSION_DENIED");
5497 return PERMISSION_DENIED;
5498 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005499 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005500 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005501}
5502
chaviw95ef3c42019-02-14 10:55:09 -08005503void SurfaceFlinger::setInputWindowsFinished() {
5504 Mutex::Autolock _l(mStateLock);
5505
5506 mPendingSyncInputWindows = false;
5507 mTransactionCV.broadcast();
5508}
chaviw5f21a5e2019-02-14 10:00:34 -08005509
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005510// ---------------------------------------------------------------------------
5511
Dan Stoza412903f2017-04-27 13:42:17 -07005512void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5513 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005514}
5515
Dan Stoza412903f2017-04-27 13:42:17 -07005516void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5517 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005518}
5519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005521 const LayerVector::Visitor& visitor) {
5522 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005523 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005524 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005525 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005526 continue;
5527 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005528 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005529 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005530 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005531 return;
5532 }
chaviwa76b2712017-09-20 12:02:26 -07005533 if (!layer->isVisible()) {
5534 return;
5535 }
5536 visitor(layer);
5537 });
5538 }
5539}
5540
Dominik Laskowski22488f62019-03-28 09:53:04 -07005541void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5542 const std::vector<int32_t>& allowedConfigs) {
5543 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005544 return;
5545 }
5546
5547 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005548 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08005549
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005550 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07005551 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005552 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005553 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005554 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005555 setDesiredActiveConfig(
5556 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005557 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005558 }
5559 }
Ady Abraham838de062019-02-04 10:24:03 -08005560}
5561
Dominik Laskowski22488f62019-03-28 09:53:04 -07005562status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005563 const std::vector<int32_t>& allowedConfigs) {
5564 ATRACE_CALL();
5565
Dominik Laskowski22488f62019-03-28 09:53:04 -07005566 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005567 return BAD_VALUE;
5568 }
5569
Ady Abraham34392f72019-04-10 11:29:27 -07005570 if (mDebugDisplayConfigSetByBackdoor) {
5571 // ignore this request as config is overridden by backdoor
5572 return NO_ERROR;
5573 }
5574
Ady Abraham838de062019-02-04 10:24:03 -08005575 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005576 const auto display = getDisplayDeviceLocked(displayToken);
5577 if (!display) {
5578 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5579 displayToken.get());
5580 } else if (display->isVirtual()) {
5581 ALOGW("Attempt to set allowed display configs for virtual display");
5582 } else {
5583 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5584 }
Ady Abraham838de062019-02-04 10:24:03 -08005585 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005586
Ady Abraham838de062019-02-04 10:24:03 -08005587 return NO_ERROR;
5588}
5589
Dominik Laskowski22488f62019-03-28 09:53:04 -07005590status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005591 std::vector<int32_t>* outAllowedConfigs) {
5592 ATRACE_CALL();
5593
Dominik Laskowski22488f62019-03-28 09:53:04 -07005594 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005595 return BAD_VALUE;
5596 }
5597
Dominik Laskowski22488f62019-03-28 09:53:04 -07005598 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005599
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005600 const auto display = getDisplayDeviceLocked(displayToken);
5601 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005602 return NAME_NOT_FOUND;
5603 }
5604
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005605 if (display->isPrimary()) {
5606 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5607 }
5608
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005609 return NO_ERROR;
5610}
5611
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005612void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005613 mFlinger->setInputWindowsFinished();
5614}
5615
Robert Carrc0df3122019-04-11 13:18:21 -07005616sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5617 BBinder *b = handle->localBinder();
5618 if (b == nullptr) {
5619 return nullptr;
5620 }
5621 auto it = mLayersByLocalBinderToken.find(b);
5622 if (it != mLayersByLocalBinderToken.end()) {
5623 return it->second.promote();
5624 }
5625 return nullptr;
5626}
5627
Alec Mouri4545a8a2019-08-08 20:05:32 -07005628void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5629 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5630}
5631
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005632} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005633
Mathias Agopian3f844832013-08-07 21:24:32 -07005634#if defined(__gl_h_)
5635#error "don't include gl/gl.h in this file"
5636#endif
5637
5638#if defined(__gl2_h_)
5639#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005640#endif