blob: e8049239bae621787253de85d2162441609e452d [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) {
242 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246 case DisplayColorSetting::ENHANCED:
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
516 // wait patiently for the window manager death
517 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700518 mWindowManager = defaultServiceManager()->getService(name);
519 if (mWindowManager != 0) {
520 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
Robert Carr720e5062018-07-30 17:45:14 -0700522 sp<IBinder> input(defaultServiceManager()->getService(
523 String16("inputflinger")));
524 if (input == nullptr) {
525 ALOGE("Failed to link to input service");
526 } else {
527 mInputFlinger = interface_cast<IInputFlinger>(input);
528 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529
Steven Thomas050b2c82017-03-06 11:45:16 -0800530 if (mVrFlinger) {
531 mVrFlinger->OnBootFinished();
532 }
533
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700535 // formerly we would just kill the process, but we now ask it to exit so it
536 // can choose where to stop the animation.
537 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700538
539 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
540 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
541 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700542
Ana Krulecbd6654b2019-02-15 15:18:15 -0800543 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 readPersistentProperties();
545 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800546
Ady Abraham97d04232019-03-05 19:48:12 -0800547 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700548 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700549 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800550
Dominik Laskowski22488f62019-03-28 09:53:04 -0700551 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800552 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800553 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800554 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800557}
558
Dan Stoza436ccf32018-06-21 12:10:12 -0700559uint32_t SurfaceFlinger::getNewTexture() {
560 {
561 std::lock_guard lock(mTexturePoolMutex);
562 if (!mTexturePool.empty()) {
563 uint32_t name = mTexturePool.back();
564 mTexturePool.pop_back();
565 ATRACE_INT("TexturePoolSize", mTexturePool.size());
566 return name;
567 }
568
569 // The pool was too small, so increase it for the future
570 ++mTexturePoolSize;
571 }
572
573 // The pool was empty, so we need to get a new texture name directly using a
574 // blocking call to the main thread
575 uint32_t name = 0;
576 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
577 return name;
578}
579
Mathias Agopian3f844832013-08-07 21:24:32 -0700580void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700581 std::lock_guard lock(mTexturePoolMutex);
582 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
583 // to actually delete this or not based on mTexturePoolSize
584 mTexturePool.push_back(texture);
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700586}
587
Wei Wangf9b05ee2017-07-19 20:59:39 -0700588// Do not call property_set on main thread which will be blocked by init
589// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700591 ALOGI( "SurfaceFlinger's main thread ready to run. "
592 "Initializing graphics H/W...");
593
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700594 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800598 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700599 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
600 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800601 auto resyncCallback =
602 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603
Ana Krulecc2870422019-01-29 19:00:58 -0800604 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700605 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700606 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800607 resyncCallback,
608 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700609 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700610 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700611 mPhaseOffsets->getOffsetThresholdForNextVsync(),
612 resyncCallback, [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 });
Ana Krulecc2870422019-01-29 19:00:58 -0800615
616 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700617
618 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
619 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800620
Kevin DuBois413287f2019-02-25 08:46:47 -0800621 mRegionSamplingThread =
622 new RegionSamplingThread(*this, *mScheduler,
623 RegionSamplingThread::EnvironmentTimingTunables());
624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700626 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700627 renderEngineFeature |= (useColorManagement ?
628 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700629 renderEngineFeature |= (useContextPriority ?
630 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700631 renderEngineFeature |=
632 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
633 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800636 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700637 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700638 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800639 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700643 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
644 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700653 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700654 // This callback is called from the vr flinger dispatch thread. We
655 // need to call signalTransaction(), which requires holding
656 // mStateLock when we're not on the main thread. Acquiring
657 // mStateLock from the vr flinger dispatch thread might trigger a
658 // deadlock in surface flinger (see b/66916578), so post a message
659 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700660 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700661 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
662 mVrFlingerRequestsDisplay = requestDisplay;
663 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
667 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700668 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700669 .value_or(0),
670 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (!mVrFlinger) {
672 ALOGE("Failed to start vrflinger");
673 }
674 }
675
Mathias Agopian92a979a2012-08-02 18:32:23 -0700676 // initialize our drawing state
677 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700678
Andy McFadden13a082e2012-08-24 10:16:42 -0700679 // set initial conditions (e.g. unblank default device)
680 initializeDisplays();
681
Steven Thomas137d4bc2019-07-25 16:55:14 -0700682 char primeShaderCache[PROPERTY_VALUE_MAX];
683 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
684 if (atoi(primeShaderCache)) {
685 getRenderEngine().primeCache();
686 }
Dan Stoza4e637772016-07-28 13:31:51 -0700687
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700689
690 const bool presentFenceReliable =
691 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
692 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693
694 if (mStartPropertySetThread->Start() != NO_ERROR) {
695 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800696 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697
Alec Mouri93bc83d2019-04-17 14:47:43 -0700698 mScheduler->setChangeRefreshRateCallback(
699 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
700 Mutex::Autolock lock(mStateLock);
701 setRefreshRateTo(type, event);
702 });
Alec Mouri7f015182019-07-11 13:56:22 -0700703 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
704 Mutex::Autolock lock(mStateLock);
705 const auto display = getDefaultDisplayDeviceLocked();
706 if (!display) {
707 // If we don't have a default display the fallback to the default
708 // refresh rate type
709 return RefreshRateType::DEFAULT;
710 }
711
712 const int configId = display->getActiveConfig();
713 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
714 if (refresh && refresh->configId == configId) {
715 return type;
716 }
717 }
718 // This should never happen, but just gracefully fallback to default.
719 return RefreshRateType::DEFAULT;
720 });
Alec Mouridc28b372019-04-18 21:17:13 -0700721 mScheduler->setGetVsyncPeriodCallback([this] {
722 Mutex::Autolock lock(mStateLock);
723 return getVsyncPeriod();
724 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700725
Dominik Laskowski22488f62019-03-28 09:53:04 -0700726 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
727 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800728
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700730}
731
Romain Guy11d63f42017-07-20 12:47:14 -0700732void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 Mutex::Autolock _l(mStateLock);
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735 char value[PROPERTY_VALUE_MAX];
736
737 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700739 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100741
742 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700743 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800744
745 property_get("persist.sys.sf.color_mode", value, "0");
746 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700760 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700764 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowski22488f62019-03-28 09:53:04 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Dominik Laskowski22488f62019-03-28 09:53:04 -0700808 Mutex::Autolock lock(mStateLock);
809
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800810 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700811 if (!displayId) {
812 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700813 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 // TODO: Not sure if display density should handled by SF any longer
816 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700819 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800820 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 }
823 return density;
824 }
825 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("ro.sf.lcd_density"); }
830 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840 info.w = hwConfig->getWidth();
841 info.h = hwConfig->getHeight();
842 // Default display viewport to display width and height
843 info.viewportW = info.w;
844 info.viewportH = info.h;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 // The density of the device is provided by a build property
848 float density = Density::getBuildDensity() / 160.0f;
849 if (density == 0) {
850 // the build doesn't provide a density -- this is wrong!
851 // use xdpi instead
852 ALOGE("ro.sf.lcd_density must be defined as a build property");
853 density = xdpi / 160.0f;
854 }
855 if (Density::getEmuDensity()) {
856 // if "qemu.sf.lcd_density" is specified, it overrides everything
857 xdpi = ydpi = density = Density::getEmuDensity();
858 density /= 160.0f;
859 }
860 info.density = density;
861
862 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863 const auto display = getDefaultDisplayDeviceLocked();
864 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
866 // This is for screenrecord
867 const Rect viewport = display->getViewport();
868 if (viewport.isValid()) {
869 info.viewportW = uint32_t(viewport.getWidth());
870 info.viewportH = uint32_t(viewport.getHeight());
871 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 } else {
873 // TODO: where should this value come from?
874 static const int TV_DENSITY = 213;
875 info.density = TV_DENSITY / 160.0f;
876 info.orientation = 0;
877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 info.xdpi = xdpi;
880 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700882 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
883 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
884 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885
Andy McFadden91b2ca82014-06-13 14:04:23 -0700886 // This is how far in advance a buffer must be queued for
887 // presentation at a given time. If you want a buffer to appear
888 // on the screen at time N, you must submit the buffer before
889 // (N - presentationDeadline).
890 //
891 // Normally it's one full refresh period (to give SF a chance to
892 // latch the buffer), but this can be reduced by configuring a
893 // DispSync offset. Any additional delays introduced by the hardware
894 // composer or panel must be accounted for here.
895 //
896 // We add an additional 1ms to allow for processing time and
897 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700898 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
900 // All non-virtual displays are currently considered secure.
901 info.secure = true;
902
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800903 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700904 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800905 std::swap(info.w, info.h);
906 }
907
Michael Wright28f24d02016-07-12 13:30:53 -0700908 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700909 }
910
Dan Stoza7f7da322014-05-02 15:26:25 -0700911 return NO_ERROR;
912}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
915 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return BAD_VALUE;
917 }
918
Ana Krulecc2870422019-01-29 19:00:58 -0800919 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return NO_ERROR;
921}
922
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
924 const auto display = getDisplayDevice(displayToken);
925 if (!display) {
926 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800927 return BAD_VALUE;
928 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700929
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700931}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700932
Ady Abraham03b02dd2019-03-21 15:40:11 -0700933void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800937 // config twice. However event generation config might have changed so we need to update it
938 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700940 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
941 mDesiredActiveConfig = info;
942 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800943
944 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 // This will trigger HWC refresh without resetting the idle timer.
946 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700947 // Start receiving vsync samples now, so that we can detect a period
948 // switch.
949 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700950 // As we called to set period, we will call to onRefreshRateChangeCompleted once
951 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700952 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700953 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700954 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800956 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700957
958 if (mRefreshRateOverlay) {
959 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
960 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800965
966 std::vector<int32_t> allowedConfig;
967 allowedConfig.push_back(mode);
968
969 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970}
971
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972void SurfaceFlinger::setActiveConfigInternal() {
973 ATRACE_CALL();
974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975 const auto display = getDefaultDisplayDeviceLocked();
976 if (!display) {
977 return;
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979
Dominik Laskowski22488f62019-03-28 09:53:04 -0700980 std::lock_guard<std::mutex> lock(mActiveConfigLock);
981 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
982
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983 display->setActiveConfig(mUpcomingActiveConfig.configId);
984
Alec Mouri754c98a2019-03-18 18:53:42 -0700985 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700986 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800989 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800990 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
991 mUpcomingActiveConfig.configId);
992 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993}
994
Ady Abraham53852a52019-05-28 18:07:44 -0700995void SurfaceFlinger::desiredActiveConfigChangeDone() {
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
998 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700999
1000 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1001 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001002 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001003}
1004
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001006 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001008 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001010 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 return true;
1012 }
1013
1014 // We received the present fence from the HWC, so we assume it successfully updated
1015 // the config, hence we update SF.
1016 mCheckPendingFence = false;
1017 setActiveConfigInternal();
1018 }
1019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 // Store the local variable to release the lock.
1021 ActiveConfigInfo desiredActiveConfig;
1022 {
1023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 if (!mDesiredActiveConfigChanged) {
1025 return false;
1026 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 desiredActiveConfig = mDesiredActiveConfig;
1028 }
1029
Dominik Laskowski22488f62019-03-28 09:53:04 -07001030 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1032 // display is not valid or we are already in the requested mode
1033 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001034 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001036 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037
Ady Abraham838de062019-02-04 10:24:03 -08001038 // Desired active config was set, it is different than the config currently in use, however
1039 // allowed configs might have change by the time we process the refresh.
1040 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001041 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001042 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001043 return false;
1044 }
Alec Mouri7f015182019-07-11 13:56:22 -07001045
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 mUpcomingActiveConfig = desiredActiveConfig;
1047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049
1050 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1051 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1052
1053 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001055 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1060 Vector<ColorMode>* outColorModes) {
1061 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001062 return BAD_VALUE;
1063 }
1064
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001066 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001068 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1069
1070 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1071 if (!displayId) {
1072 return NAME_NOT_FOUND;
1073 }
1074
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001076 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001077 }
Michael Wright28f24d02016-07-12 13:30:53 -07001078 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001079
1080 // If it's built-in display and the configuration claims it's not wide color capable,
1081 // filter out all wide color modes. The typical reason why this happens is that the
1082 // hardware is not good enough to support GPU composition of wide color, and thus the
1083 // OEMs choose to disable this capability.
1084 if (isInternalDisplay && !hasWideColorDisplay) {
1085 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1086 isWideColorMode);
1087 } else {
1088 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1089 }
Michael Wright28f24d02016-07-12 13:30:53 -07001090
1091 return NO_ERROR;
1092}
1093
Daniel Solomon42d04562019-01-20 21:03:19 -08001094status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1095 ui::DisplayPrimaries &primaries) {
1096 if (!displayToken) {
1097 return BAD_VALUE;
1098 }
1099
1100 // Currently we only support this API for a single internal display.
1101 if (getInternalDisplayToken() != displayToken) {
1102 return BAD_VALUE;
1103 }
1104
1105 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1106 return NO_ERROR;
1107}
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1110 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001111 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001112 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001113 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001114}
1115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001117 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118 Vector<ColorMode> modes;
1119 getDisplayColorModes(displayToken, &modes);
1120 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1121 if (mode < ColorMode::NATIVE || !exists) {
1122 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1123 decodeColorMode(mode).c_str(), mode, displayToken.get());
1124 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001125 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDevice(displayToken);
1127 if (!display) {
1128 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1129 decodeColorMode(mode).c_str(), mode, displayToken.get());
1130 } else if (display->isVirtual()) {
1131 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1132 decodeColorMode(mode).c_str(), mode);
1133 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001134 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
Lloyd Piquef5275482019-01-29 18:42:42 -08001135 RenderIntent::COLORIMETRIC,
1136 Dataspace::UNKNOWN);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 }
1138 }));
1139
Michael Wright28f24d02016-07-12 13:30:53 -07001140 return NO_ERROR;
1141}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001142
Svetoslavd85084b2014-03-20 10:28:31 -07001143status_t SurfaceFlinger::clearAnimationFrameStats() {
1144 Mutex::Autolock _l(mStateLock);
1145 mAnimFrameTracker.clearStats();
1146 return NO_ERROR;
1147}
1148
1149status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1150 Mutex::Autolock _l(mStateLock);
1151 mAnimFrameTracker.getStats(outStats);
1152 return NO_ERROR;
1153}
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1156 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 Mutex::Autolock _l(mStateLock);
1158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 const auto display = getDisplayDeviceLocked(displayToken);
1160 if (!display) {
1161 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001162 return BAD_VALUE;
1163 }
1164
Peiyong Linfb069302018-04-25 14:34:31 -07001165 // At this point the DisplayDeivce should already be set up,
1166 // meaning the luminance information is already queried from
1167 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001169 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1170 capabilities.getDesiredMaxLuminance(),
1171 capabilities.getDesiredMaxAverageLuminance(),
1172 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001173
1174 return NO_ERROR;
1175}
1176
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001177status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1178 ui::PixelFormat* outFormat,
1179 ui::Dataspace* outDataspace,
1180 uint8_t* outComponentMask) const {
1181 if (!outFormat || !outDataspace || !outComponentMask) {
1182 return BAD_VALUE;
1183 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001184 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001185 if (!display || !display->getId()) {
1186 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1187 return BAD_VALUE;
1188 }
1189 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1190 outDataspace, outComponentMask);
1191}
1192
Kevin DuBois74e53772018-11-19 10:52:38 -08001193status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1194 bool enable, uint8_t componentMask,
1195 uint64_t maxFrames) const {
1196 const auto display = getDisplayDevice(displayToken);
1197 if (!display || !display->getId()) {
1198 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1199 return BAD_VALUE;
1200 }
1201
1202 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1203 componentMask, maxFrames);
1204}
1205
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001206status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1207 uint64_t maxFrames, uint64_t timestamp,
1208 DisplayedFrameStats* outStats) const {
1209 const auto display = getDisplayDevice(displayToken);
1210 if (!display || !display->getId()) {
1211 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1212 return BAD_VALUE;
1213 }
1214
1215 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1216 outStats);
1217}
1218
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001219status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1220 if (!outSupported) {
1221 return BAD_VALUE;
1222 }
1223 *outSupported = getRenderEngine().supportsProtectedContent();
1224 return NO_ERROR;
1225}
1226
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001227status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1228 bool* outIsWideColorDisplay) const {
1229 if (!displayToken || !outIsWideColorDisplay) {
1230 return BAD_VALUE;
1231 }
1232 Mutex::Autolock _l(mStateLock);
1233 const auto display = getDisplayDeviceLocked(displayToken);
1234 if (!display) {
1235 return BAD_VALUE;
1236 }
Peiyong Linff84a152019-05-17 18:36:19 -07001237
1238 // Use hasWideColorDisplay to override built-in display.
1239 const auto displayId = display->getId();
1240 if (displayId && displayId == getInternalDisplayIdLocked()) {
1241 *outIsWideColorDisplay = hasWideColorDisplay;
1242 return NO_ERROR;
1243 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001244 *outIsWideColorDisplay = display->hasWideColorGamut();
1245 return NO_ERROR;
1246}
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001249 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 if (mInjectVSyncs == enable) {
1253 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255
Ana Krulecc2870422019-01-29 19:00:58 -08001256 auto resyncCallback =
1257 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001258
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001259 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001261 if (enable) {
1262 ALOGV("VSync Injections enabled");
1263 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001264 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001265 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001266 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001267 impl::EventThread::InterceptVSyncsCallback(),
1268 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001269 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 } else {
1272 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001273 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1274 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 }
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001278 }));
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 return NO_ERROR;
1281}
1282
1283status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001284 Mutex::Autolock _l(mStateLock);
1285
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001286 if (!mInjectVSyncs) {
1287 ALOGE("VSync Injections not enabled");
1288 return BAD_VALUE;
1289 }
1290 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1291 ALOGV("Injecting VSync inside SurfaceFlinger");
1292 mVSyncInjector->onInjectSyncEvent(when);
1293 }
1294 return NO_ERROR;
1295}
1296
Lloyd Pique755e3192018-01-31 16:46:15 -08001297status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1298 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001299 // Try to acquire a lock for 1s, fail gracefully
1300 const status_t err = mStateLock.timedLock(s2ns(1));
1301 const bool locked = (err == NO_ERROR);
1302 if (!locked) {
1303 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1304 return TIMED_OUT;
1305 }
1306
1307 outLayers->clear();
1308 mCurrentState.traverseInZOrder([&](Layer* layer) {
1309 outLayers->push_back(layer->getLayerDebugInfo());
1310 });
1311
1312 mStateLock.unlock();
1313 return NO_ERROR;
1314}
1315
Peiyong Linc6780972018-10-28 15:24:08 -07001316status_t SurfaceFlinger::getCompositionPreference(
1317 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1318 Dataspace* outWideColorGamutDataspace,
1319 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001320 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001321 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001324 return NO_ERROR;
1325}
1326
Dan Stozaec460082018-12-17 15:35:09 -08001327status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1328 const sp<IBinder>& stopLayerHandle,
1329 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001330 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001331 return BAD_VALUE;
1332 }
1333 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001334 return NO_ERROR;
1335}
1336
Dan Stozaec460082018-12-17 15:35:09 -08001337status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001338 if (!listener) {
1339 return BAD_VALUE;
1340 }
Dan Stozaec460082018-12-17 15:35:09 -08001341 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001342 return NO_ERROR;
1343}
Dan Gittik57e63c52019-01-18 16:37:54 +00001344
1345status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1346 bool* outSupport) const {
1347 if (!displayToken || !outSupport) {
1348 return BAD_VALUE;
1349 }
1350 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1351 if (!displayId) {
1352 return NAME_NOT_FOUND;
1353 }
1354 *outSupport =
1355 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1356 return NO_ERROR;
1357}
1358
1359status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1360 float brightness) const {
1361 if (!displayToken) {
1362 return BAD_VALUE;
1363 }
1364 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1365 if (!displayId) {
1366 return NAME_NOT_FOUND;
1367 }
1368 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1369}
1370
Ady Abraham8532d012019-05-08 14:50:56 -07001371status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1372 PowerHint powerHint = static_cast<PowerHint>(hintId);
1373
1374 if (powerHint == PowerHint::INTERACTION) {
1375 mScheduler->notifyTouchEvent();
1376 }
1377
1378 return NO_ERROR;
1379}
1380
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001381// ----------------------------------------------------------------------------
1382
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001383sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001384 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001385 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001386 Mutex::Autolock lock(mStateLock);
1387 return getVsyncPeriod();
1388 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001389
Ana Krulecc2870422019-01-29 19:00:58 -08001390 const auto& handle =
1391 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001392
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001393 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1394 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001395}
1396
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398
1399void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001400 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001401}
1402
1403void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001404 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001405 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406}
1407
1408void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001409 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001410 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001411}
1412
1413void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001414 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001415 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001416}
1417
1418status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001419 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001420 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001421}
1422
1423status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001424 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001425 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 if (res == NO_ERROR) {
1427 msg->wait();
1428 }
1429 return res;
1430}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001431
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001432void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001433 do {
1434 waitForEvent();
1435 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001436}
1437
Dominik Laskowski83b88212018-12-11 13:34:06 -08001438nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001439 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001440 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1441 return 0;
1442 }
1443
1444 const auto config = getHwComposer().getActiveConfig(*displayId);
1445 return config ? config->getVsyncPeriod() : 0;
1446}
1447
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001448void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1449 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001450 ATRACE_NAME("SF onVsync");
1451
Steven Thomas3cfac282017-02-06 12:29:30 -08001452 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 return;
1456 }
1457
Dominik Laskowski075d3172018-05-24 15:50:06 -07001458 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001459 return;
1460 }
1461
Dominik Laskowski075d3172018-05-24 15:50:06 -07001462 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001463 // For now, we don't do anything with external display vsyncs.
1464 return;
1465 }
1466
Alec Mourif8e689c2019-05-20 18:32:22 -07001467 bool periodFlushed = false;
1468 mScheduler->addResyncSample(timestamp, &periodFlushed);
1469 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001470 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001471 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001472}
1473
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001474void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001475 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1476 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001477}
1478
Ady Abraham261614e2019-07-10 17:53:12 -07001479bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001480 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001481}
1482
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001483void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001484 const auto display = getDefaultDisplayDeviceLocked();
1485 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 return;
1487 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001488 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001489
Ana Krulec7d1d6832018-12-27 11:10:09 -08001490 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001491 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001492 if (!refreshRateConfig) {
1493 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001494 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495 }
Ady Abraham1902d072019-03-01 17:18:59 -08001496
Alec Mouri0a1cc962019-03-14 12:33:02 -07001497 const int desiredConfigId = refreshRateConfig->configId;
1498
Dominik Laskowski22488f62019-03-28 09:53:04 -07001499 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001500 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1501 return;
1502 }
1503
Dominik Laskowski22488f62019-03-28 09:53:04 -07001504 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001505}
1506
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001507void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001508 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001509 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001510 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511
Lloyd Piqueba04e622017-12-14 17:11:26 -08001512 // Ignore events that do not have the right sequenceId.
1513 if (sequenceId != getBE().mComposerSequenceId) {
1514 return;
1515 }
1516
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 // Only lock if we're not on the main thread. This function is normally
1518 // called on a hwbinder thread, but for the primary display it's called on
1519 // the main thread with the state lock already held, so don't attempt to
1520 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001521 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001524
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001525 if (std::this_thread::get_id() == mMainThreadId) {
1526 // Process all pending hot plug events immediately if we are on the main thread.
1527 processDisplayHotplugEventsLocked();
1528 }
1529
Lloyd Piqueba04e622017-12-14 17:11:26 -08001530 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001531}
1532
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001533void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001534 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001535 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001537 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001538 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001539}
1540
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001541void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001542 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001543
1544 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1545 // display power state.
1546 postMessageAsync(new LambdaMessage(
1547 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1548}
1549
1550void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1551 ATRACE_CALL();
1552
Ady Abraham27c70212019-06-11 10:52:26 -07001553 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1554
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001555 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001556 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1557 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001558 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001559 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001560 }
Mathias Agopian86303202012-07-24 22:46:10 -07001561}
1562
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001564void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001565 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566 // Clear the drawing state so that the logic inside of
1567 // handleTransactionLocked will fire. It will determine the delta between
1568 // mCurrentState and mDrawingState and re-apply all changes when we make the
1569 // transition.
1570 mDrawingState.displays.clear();
1571 mDisplays.clear();
1572}
1573
Steven Thomas050b2c82017-03-06 11:45:16 -08001574void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001575 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001576 if (!mVrFlinger)
1577 return;
1578 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001579 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001580 return;
1581 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582
Lloyd Pique441d5042018-10-18 16:49:51 -07001583 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 ALOGE("Vr flinger is only supported for remote hardware composer"
1585 " service connections. Ignoring request to transition to vr"
1586 " flinger.");
1587 mVrFlingerRequestsDisplay = false;
1588 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001589 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001590
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Steven Thomas0123ac62018-07-12 11:32:34 -07001593 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001594 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001595
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001596 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001597
1598 // Clear out all the output layers from the composition engine for all
1599 // displays before destroying the hardware composer interface. This ensures
1600 // any HWC layers are destroyed through that interface before it becomes
1601 // invalid.
1602 for (const auto& [token, displayDevice] : mDisplays) {
1603 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1604 compositionengine::Output::OutputLayers());
1605 }
1606
Steven Thomas0123ac62018-07-12 11:32:34 -07001607 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1608 // called below. Clear the reference now so we don't accidentally use it
1609 // later.
1610 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001611
Steven Thomasb02664d2017-07-26 18:48:28 -07001612 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001614 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001615
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001617 // Delete the current instance before creating the new one
1618 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1619 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1620 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1621 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001624 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001625
1626 if (vrFlingerRequestsDisplay) {
1627 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001628 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001629
1630 mVisibleRegionsDirty = true;
1631 invalidateHwcGeometry();
1632
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001633 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001634 display = getDefaultDisplayDeviceLocked();
1635 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001636 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001639 const nsecs_t vsyncPeriod = getVsyncPeriod();
1640 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001641
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001642 // The present fences returned from vr_hwc are not an accurate
1643 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001644 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001645
Steven Thomasb02664d2017-07-26 18:48:28 -07001646 // Use phase of 0 since phase is not known.
1647 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001648 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001649 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001650
Ana Krulecc2870422019-01-29 19:00:58 -08001651 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001652
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001653 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001654 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655}
1656
Ady Abrahambe0f9482019-04-24 15:41:53 -07001657bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1658 // We are storing the last 2 present fences. If sf's phase offset is to be
1659 // woken up before the actual vsync but targeting the next vsync, we need to check
1660 // fence N-2
1661 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001662 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001663 ? mPreviousPresentFences[0]
1664 : mPreviousPresentFences[1];
1665
1666 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1667}
1668
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001669void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001670 DisplayStatInfo stats;
1671 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001672 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001673 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001674 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001675 mPhaseOffsets->getOffsetThresholdForNextVsync()
1676 ? presentTime
1677 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001678}
1679
Dominik Laskowski22488f62019-03-28 09:53:04 -07001680void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001681 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001682 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001683 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001684 // calculate the expected present time once and use the cached
1685 // value throughout this frame to make sure all layers are
1686 // seeing this same value.
1687 populateExpectedPresentTime();
1688
Ady Abraham50204dd2019-07-19 15:47:11 -07001689 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1690 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1691 mHadDeviceComposition && frameMissed};
1692 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1693 mHadClientComposition && frameMissed};
1694
Alec Mouricc0fc602019-02-26 21:45:19 -08001695 if (frameMissed) {
1696 mFrameMissedCount++;
1697 mTimeStats->incrementMissedFrames();
1698 }
1699
Alec Mouri40189b02019-03-05 15:07:54 -08001700 if (hwcFrameMissed) {
1701 mHwcFrameMissedCount++;
1702 }
1703
1704 if (gpuFrameMissed) {
1705 mGpuFrameMissedCount++;
1706 }
1707
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001708 if (mUseSmart90ForVideo) {
1709 // This call is made each time SF wakes up and creates a new frame. It is part
1710 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001711 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001712 }
1713
Ady Abrahamb838aed2019-02-12 15:30:16 -08001714 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001715 break;
1716 }
1717
Ady Abraham4658e112019-07-22 13:07:26 -07001718 if (frameMissed && mPropagateBackpressure) {
1719 if ((hwcFrameMissed && !gpuFrameMissed) ||
1720 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001721 signalLayerUpdate();
1722 break;
1723 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001724 }
Dan Stoza50182882016-07-08 12:02:20 -07001725
Steven Thomas050b2c82017-03-06 11:45:16 -08001726 // Now that we're going to make it to the handleMessageTransaction()
1727 // call below it's safe to call updateVrFlinger(), which will
1728 // potentially trigger a display handoff.
1729 updateVrFlinger();
1730
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731 bool refreshNeeded = handleMessageTransaction();
1732 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001733
1734 updateCursorAsync();
1735 updateInputFlinger();
1736
Dan Stoza58784442014-12-02 16:58:17 -08001737 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001738 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001739 // Signal a refresh if a transaction modified the window state,
1740 // a new buffer was latched, or if HWC has requested a full
1741 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001742 signalRefresh();
1743 }
1744 break;
1745 }
1746 case MessageQueue::REFRESH: {
1747 handleMessageRefresh();
1748 break;
1749 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001750 }
1751}
1752
Dan Stoza6b9454d2014-11-07 16:00:59 -08001753bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001754 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001755 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001756
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001757 bool flushedATransaction = flushTransactionQueues();
1758
1759 bool runHandleTransaction = transactionFlags &&
1760 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1761
1762 if (runHandleTransaction) {
1763 handleTransaction(eTransactionMask);
1764 } else {
1765 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001766 }
1767
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001768 if (transactionFlushNeeded()) {
1769 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001770 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001771
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001772 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773}
1774
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001776 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001777
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001778 mRefreshPending = false;
1779
Lloyd Piqueab039b52019-02-13 14:22:42 -08001780 compositionengine::CompositionRefreshArgs refreshArgs;
1781 for (const auto& [_, display] : mDisplays) {
1782 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1783 }
1784 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1785 auto compositionLayer = layer->getCompositionLayer();
1786 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1787 });
1788
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001789 const bool repaintEverything = mRepaintEverything.exchange(false);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001790 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001791 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001792 calculateWorkingSet();
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001793 for (const auto& [token, displayDevice] : mDisplays) {
1794 auto display = displayDevice->getCompositionDisplay();
1795 display->beginFrame();
1796 display->prepareFrame();
1797 doDebugFlashRegions(displayDevice, repaintEverything);
1798 doComposition(displayDevice, repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001799 }
1800
David Sodmanfa9b2af2017-12-24 13:28:59 -08001801 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001802 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001803
Lloyd Pique66d68602019-02-13 14:23:31 -08001804 mHadClientComposition =
1805 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1806 auto& displayDevice = tokenDisplayPair.second;
1807 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1808 });
1809 mHadDeviceComposition =
1810 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1811 auto& displayDevice = tokenDisplayPair.second;
1812 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1813 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001814
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001815 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001816
David Sodman7e4ae112018-02-09 15:02:28 -08001817 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001818 if (mVisibleRegionsDirty) {
1819 mVisibleRegionsDirty = false;
1820 if (mTracingEnabled) {
1821 mTracing.notify("visibleRegionsDirty");
1822 }
1823 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001824
1825 if (mCompositionEngine->needsAnotherUpdate()) {
1826 signalLayerUpdate();
1827 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001829
David Sodmanfa9b2af2017-12-24 13:28:59 -08001830
1831bool SurfaceFlinger::handleMessageInvalidate() {
1832 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001833 bool refreshNeeded = handlePageFlip();
1834
Vishnu Nair4351ad52019-02-11 14:13:02 -08001835 if (mVisibleRegionsDirty) {
1836 computeLayerBounds();
1837 }
1838
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001839 for (auto& layer : mLayersPendingRefresh) {
1840 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001841 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001842 invalidateLayerStack(layer, visibleReg);
1843 }
1844 mLayersPendingRefresh.clear();
1845 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001846}
1847
David Sodman79bba0e2018-08-05 18:07:49 -07001848void SurfaceFlinger::calculateWorkingSet() {
1849 ATRACE_CALL();
1850 ALOGV(__FUNCTION__);
1851
Lloyd Piquef5275482019-01-29 18:42:42 -08001852 const bool updatingGeometryThisFrame = mGeometryInvalid;
1853 mGeometryInvalid = false;
1854
Lloyd Pique05ed22e2019-08-09 12:20:51 -07001855 // Latch the frontend layer composition state for each layer being
1856 // composed.
1857 for (const auto& [token, displayDevice] : mDisplays) {
1858 auto display = displayDevice->getCompositionDisplay();
1859 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1860 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1861 updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001862 }
1863 }
1864
1865 if (CC_UNLIKELY(updatingGeometryThisFrame)) {
1866 for (const auto& [token, displayDevice] : mDisplays) {
1867 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquea83776c2019-01-29 18:42:32 -08001868 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001869
Lloyd Piquea83776c2019-01-29 18:42:32 -08001870 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquef5275482019-01-29 18:42:42 -08001871 // Assign a simple Z order sequence to each visible layer.
1872 layer->editState().z = zOrder++;
David Sodman79bba0e2018-08-05 18:07:49 -07001873 }
1874 }
1875 }
1876
Lloyd Piquef5275482019-01-29 18:42:42 -08001877 // Determine the color configuration of each output
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 for (const auto& [token, displayDevice] : mDisplays) {
1879 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001880
Lloyd Piquef5275482019-01-29 18:42:42 -08001881 ColorMode colorMode = ColorMode::NATIVE;
1882 Dataspace dataspace = Dataspace::UNKNOWN;
1883 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1884 if (useColorManagement) {
1885 pickColorMode(displayDevice, &colorMode, &dataspace, &renderIntent);
1886 }
1887 display->setColorMode(colorMode, dataspace, renderIntent, mColorSpaceAgnosticDataspace);
1888 }
1889
1890 for (const auto& [token, displayDevice] : mDisplays) {
1891 auto display = displayDevice->getCompositionDisplay();
1892
1893 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquec358b522019-08-09 12:21:21 -07001894 if (mDebugDisableHWC || mDebugRegion) {
1895 layer->editState().forceClientComposition = true;
1896 }
1897
Lloyd Piquef5275482019-01-29 18:42:42 -08001898 // Update the composition state of the output layer, as needed
1899 // recomputing it from the state given by the front-end layer.
1900 layer->updateCompositionState(updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001901
Lloyd Piquef5275482019-01-29 18:42:42 -08001902 // Send the updated state to the HWC, if appropriate.
1903 layer->writeStateToHWC(updatingGeometryThisFrame);
1904 }
1905 }
1906
1907 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1908 for (const auto& [token, displayDevice] : mDisplays) {
1909 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001910 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001911 }
Lloyd Piquef5275482019-01-29 18:42:42 -08001912 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001913 }
David Sodman79bba0e2018-08-05 18:07:49 -07001914}
1915
Lloyd Pique32cbe282018-10-19 13:09:22 -07001916void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1917 bool repaintEverything) {
1918 auto display = displayDevice->getCompositionDisplay();
1919 const auto& displayState = display->getState();
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 // is debugging enabled
1922 if (CC_LIKELY(!mDebugRegion))
1923 return;
1924
Lloyd Pique32cbe282018-10-19 13:09:22 -07001925 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001926 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001927 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001928 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001929 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001930 // redraw the whole screen
Lloyd Pique688abd42019-02-15 15:42:24 -08001931 display->composeSurfaces(dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001933 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 }
1935 }
1936
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001937 displayDevice->getCompositionDisplay()->postFramebuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938
1939 if (mDebugRegion > 1) {
1940 usleep(mDebugRegion * 1000);
1941 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001942
Lloyd Pique66d68602019-02-13 14:23:31 -08001943 displayDevice->getCompositionDisplay()->prepareFrame();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944}
1945
Ana Krulece588e312018-09-18 12:32:24 -07001946void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1947 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 // Update queue of past composite+present times and determine the
1949 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001950 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001952 while (!getBE().mCompositePresentTimes.empty()) {
1953 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Cached values should have been updated before calling this method,
1955 // which helps avoid duplicate syscalls.
1956 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1957 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1958 break;
1959 }
1960 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001961 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 }
1963
1964 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001965 while (getBE().mCompositePresentTimes.size() > 16) {
1966 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 }
1968
Ana Krulece588e312018-09-18 12:32:24 -07001969 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001970}
1971
Ana Krulece588e312018-09-18 12:32:24 -07001972void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1973 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974 // Integer division and modulo round toward 0 not -inf, so we need to
1975 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001976 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1977 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1978 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979
Ana Krulec757f63a2019-01-25 10:46:18 -08001980 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001981 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001982 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001983 }
1984
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // Snap the latency to a value that removes scheduling jitter from the
1986 // composition and present times, which often have >1ms of jitter.
1987 // Reducing jitter is important if an app attempts to extrapolate
1988 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001989 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001991 nsecs_t bias = stats.vsyncPeriod / 2;
1992 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1993 nsecs_t snappedCompositeToPresentLatency =
1994 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995
David Sodman99974d22017-11-28 12:04:33 -08001996 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001997 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1998 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001999 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002000}
2001
David Sodman2b406362017-12-15 13:33:47 -08002002void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002003{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 ATRACE_CALL();
2005 ALOGV("postComposition");
2006
Brian Anderson3546a3f2016-07-14 11:51:14 -07002007 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002008 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002009 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002010 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 }
2012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002014 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002015
David Sodman73beded2017-11-15 11:56:06 -08002016 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002018 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002020 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2021 ->getRenderSurface()
2022 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002023 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 } else {
2025 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2026 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002029 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2030 mPreviousPresentFences[0] = displayDevice
2031 ? getHwComposer().getPresentFence(*displayDevice->getId())
2032 : Fence::NO_FENCE;
2033 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035
Ana Krulece588e312018-09-18 12:32:24 -07002036 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002037 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038
Lloyd Piqueab039b52019-02-13 14:22:42 -08002039 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2040 // be sampled a little later than when we started doing work for this frame,
2041 // but that should be okay since updateCompositorTiming has snapping logic.
2042 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2043 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002044 CompositorTiming compositorTiming;
2045 {
David Sodman99974d22017-11-28 12:04:33 -08002046 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2047 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002048 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049
Robert Carr2047fae2016-11-28 14:09:09 -08002050 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002051 bool frameLatched =
2052 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2053 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002054 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002055 recordBufferingStats(layer->getName().string(),
2056 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002057 }
Robert Carr2047fae2016-11-28 14:09:09 -08002058 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002059
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002060 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002061 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002062 }
2063
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002064 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002065 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2066 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002067 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002068 }
2069 }
2070
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002071 if (mAnimCompositionPending) {
2072 mAnimCompositionPending = false;
2073
Brian Anderson4e606e32017-03-16 15:34:57 -07002074 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002075 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002076 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002077 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002078 // The HWC doesn't support present fences, so use the refresh
2079 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 const nsecs_t presentTime =
2081 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082 mAnimFrameTracker.setActualPresentTime(presentTime);
2083 }
2084 mAnimFrameTracker.advanceFrame();
2085 }
Dan Stozab90cf072015-03-05 11:05:59 -08002086
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002087 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002088 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002089 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002090 }
2091
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002092 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002093
Lloyd Pique32cbe282018-10-19 13:09:22 -07002094 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2095 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002096 return;
2097 }
2098
2099 nsecs_t currentTime = systemTime();
2100 if (mHasPoweredOff) {
2101 mHasPoweredOff = false;
2102 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002103 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002104 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002105 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2106 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002107 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002108 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002109 }
David Sodman4a36e932017-11-07 14:29:47 -08002110 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002111 }
David Sodman4a36e932017-11-07 14:29:47 -08002112 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002113
2114 {
2115 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002116 if (mTexturePool.size() < mTexturePoolSize) {
2117 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002118 const size_t offset = mTexturePool.size();
2119 mTexturePool.resize(mTexturePoolSize);
2120 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2121 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002122 } else if (mTexturePool.size() > mTexturePoolSize) {
2123 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2124 const size_t offset = mTexturePoolSize;
2125 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2126 mTexturePool.resize(mTexturePoolSize);
2127 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002128 }
2129 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002130
Ady Abrahambe0f9482019-04-24 15:41:53 -07002131 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002132 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002133
Kevin DuBois413287f2019-02-25 08:46:47 -08002134 if (mLumaSampling && mRegionSamplingThread) {
2135 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002136 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002137
2138 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2139 // side-effect of getTotalSize(), so we check that again here
2140 if (ATRACE_ENABLED()) {
2141 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2142 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002143}
2144
Vishnu Nair4351ad52019-02-11 14:13:02 -08002145void SurfaceFlinger::computeLayerBounds() {
2146 for (const auto& pair : mDisplays) {
2147 const auto& displayDevice = pair.second;
2148 const auto display = displayDevice->getCompositionDisplay();
2149 for (const auto& layer : mDrawingState.layersSortedByZ) {
2150 // only consider the layers on the given layer stack
2151 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002152 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002153 }
2154
2155 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2156 }
2157 }
2158}
2159
Mathias Agopiancd60f992012-08-16 16:28:27 -07002160void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161 ATRACE_CALL();
2162 ALOGV("rebuildLayerStacks");
2163
Mathias Agopiancd60f992012-08-16 16:28:27 -07002164 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002165 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002166 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002167 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002168
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002169 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002170 const auto& displayDevice = pair.second;
2171 auto display = displayDevice->getCompositionDisplay();
2172 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002173 Region opaqueRegion;
2174 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002175 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002176 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002177 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002178 const ui::Transform& tr = displayState.transform;
2179 const Rect bounds = displayState.bounds;
2180 if (displayState.isEnabled) {
2181 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002182
Jeff Sharkey76488112017-02-27 14:15:18 -07002183 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002184 auto compositionLayer = layer->getCompositionLayer();
2185 if (compositionLayer == nullptr) {
2186 return;
2187 }
2188
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002190 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2191 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2192
Lloyd Pique07e33212018-12-18 16:33:37 -08002193 bool needsOutputLayer = false;
2194
Lloyd Piqueef36b002019-01-23 17:52:04 -08002195 if (display->belongsInOutput(layer->getLayerStack(),
2196 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 Region drawRegion(tr.transform(
2198 layer->visibleNonTransparentRegion));
2199 drawRegion.andSelf(bounds);
2200 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002201 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002202 }
Chia-I Wu83806892017-11-16 10:50:20 -08002203 }
2204
Lloyd Pique07e33212018-12-18 16:33:37 -08002205 if (needsOutputLayer) {
2206 layersSortedByZ.emplace_back(
2207 display->getOrCreateOutputLayer(displayId, compositionLayer,
2208 layerFE));
2209 deprecated_layersSortedByZ.add(layer);
2210
2211 auto& outputLayerState = layersSortedByZ.back()->editState();
2212 outputLayerState.visibleRegion =
2213 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2214 } else if (displayId) {
2215 // For layers that are being removed from a HWC display,
2216 // and that have queued frames, add them to a a list of
2217 // released layers so we can properly set a fence.
2218 bool hasExistingOutputLayer =
2219 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2220 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2221 mLayersWithQueuedFrames.cend(),
2222 layer) != mLayersWithQueuedFrames.cend();
2223
2224 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002225 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002226 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002227 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002228 });
2229 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002230
2231 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002232 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002233
2234 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002235
2236 Region undefinedRegion{bounds};
2237 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2238
2239 display->editState().undefinedRegion = undefinedRegion;
2240 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002241 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002242 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002243}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002244
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002245// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002247// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002248// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002249// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002250// The returned HDR data space is one of
2251// - Dataspace::UNKNOWN
2252// - Dataspace::BT2020_HLG
2253// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002254Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2255 Dataspace* outHdrDataSpace,
2256 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002257 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002258 *outHdrDataSpace = Dataspace::UNKNOWN;
2259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002261 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002262 case Dataspace::V0_SCRGB:
2263 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002264 case Dataspace::BT2020:
2265 case Dataspace::BT2020_ITU:
2266 case Dataspace::BT2020_LINEAR:
2267 case Dataspace::DISPLAY_BT2020:
2268 bestDataSpace = Dataspace::DISPLAY_BT2020;
2269 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002271 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 case Dataspace::BT2020_PQ:
2274 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002275 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276 *outHdrDataSpace = Dataspace::BT2020_PQ;
Lloyd Piquef5275482019-01-29 18:42:42 -08002277 *outIsHdrClientComposition =
2278 layer->getCompositionLayer()->getState().frontEnd.forceClientComposition;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002279 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002280 case Dataspace::BT2020_HLG:
2281 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002282 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 // When there's mixed PQ content and HLG content, we set the HDR
2284 // data space to be BT2020_PQ and convert HLG to PQ.
2285 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2286 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002287 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288 break;
2289 default:
2290 break;
2291 }
Romain Guy54f154a2017-10-24 21:40:32 +01002292 }
2293
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002295}
2296
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2299 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2301 *outMode = ColorMode::NATIVE;
2302 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002305 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002306
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002308 bool isHdrClientComposition = false;
2309 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002311 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2312
Peiyong Lina3ea5592019-02-10 14:45:00 -08002313 switch (mForceColorMode) {
2314 case ColorMode::SRGB:
2315 bestDataSpace = Dataspace::V0_SRGB;
2316 break;
2317 case ColorMode::DISPLAY_P3:
2318 bestDataSpace = Dataspace::DISPLAY_P3;
2319 break;
2320 default:
2321 break;
2322 }
2323
Peiyong Lindfde5112018-06-05 10:58:41 -07002324 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002325 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2326 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002327 if (isHdr) {
2328 bestDataSpace = hdrDataSpace;
2329 }
2330
Chia-I Wu0d711262018-05-21 15:19:35 -07002331 RenderIntent intent;
2332 switch (mDisplayColorSetting) {
2333 case DisplayColorSetting::MANAGED:
2334 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002335 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002336 break;
2337 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002338 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002339 break;
2340 default: // vendor display color setting
2341 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2342 break;
2343 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002344
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002345 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002346}
2347
Lloyd Pique32cbe282018-10-19 13:09:22 -07002348void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002349 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002350 ALOGV("doComposition");
2351
Lloyd Pique32cbe282018-10-19 13:09:22 -07002352 auto display = displayDevice->getCompositionDisplay();
2353 const auto& displayState = display->getState();
2354
2355 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002356 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002357 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002358
David Sodmanfa9b2af2017-12-24 13:28:59 -08002359 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002360 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002361
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002363 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002364 }
Lloyd Pique35fca9d2019-02-13 14:24:11 -08002365 displayDevice->getCompositionDisplay()->postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002366}
2367
David Sodmanfa9b2af2017-12-24 13:28:59 -08002368void SurfaceFlinger::postFrame()
2369{
2370 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002371 const auto display = getDefaultDisplayDeviceLocked();
2372 if (display && getHwComposer().isConnected(*display->getId())) {
2373 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2375 logFrameStats();
2376 }
2377 }
2378}
2379
Mathias Agopian87baae12012-07-31 12:38:26 -07002380void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381{
Mathias Agopian841cde52012-03-01 15:44:37 -08002382 ATRACE_CALL();
2383
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002384 // here we keep a copy of the drawing state (that is the state that's
2385 // going to be overwritten by handleTransactionLocked()) outside of
2386 // mStateLock so that the side-effects of the State assignment
2387 // don't happen with mStateLock held (which can cause deadlocks).
2388 State drawingState(mDrawingState);
2389
Mathias Agopianca4d3602011-05-19 15:38:14 -07002390 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002391 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopianca4d3602011-05-19 15:38:14 -07002393 // Here we're guaranteed that some transaction flags are set
2394 // so we can call handleTransactionLocked() unconditionally.
2395 // We call getTransactionFlags(), which will also clear the flags,
2396 // with mStateLock held to guarantee that mCurrentState won't change
2397 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002398
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002399 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002401 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002402
Mathias Agopianca4d3602011-05-19 15:38:14 -07002403 mDebugInTransaction = 0;
2404 invalidateHwcGeometry();
2405 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002406}
2407
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2409 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 const std::optional<DisplayIdentificationInfo> info =
2411 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414 continue;
2415 }
2416
Lloyd Piqueba04e622017-12-14 17:11:26 -08002417 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002419 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002420 mPhysicalDisplayTokens[info->id] = new BBinder();
2421 DisplayDeviceState state;
2422 state.displayId = info->id;
2423 state.isSecure = true; // All physical displays are currently considered secure.
2424 state.displayName = info->name;
2425 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2426 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002427 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002428 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002429 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2432 if (index >= 0) {
2433 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2434 mInterceptor->saveDisplayDeletion(state.sequenceId);
2435 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002436 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438 }
2439
2440 processDisplayChangesLocked();
2441 }
2442
2443 mPendingHotplugEvents.clear();
2444}
2445
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002446void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002447 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2448 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002449}
2450
Lloyd Pique99d3da52018-01-22 17:48:03 -08002451sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002453 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 const sp<IGraphicBufferProducer>& producer) {
2455 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002456 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002458 creationArgs.isSecure = state.isSecure;
2459 creationArgs.displaySurface = dispSurface;
2460 creationArgs.hasWideColorGamut = false;
2461 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002462 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002464 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465 creationArgs.isPrimary = isInternalDisplay;
2466
2467 if (useColorManagement && displayId) {
2468 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002470 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002471 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002473
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002476 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477 }
tangrobin6753a022018-08-10 10:58:54 +08002478 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 if (displayId) {
2481 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002482 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002484 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485
Lloyd Pique90c115d2018-09-18 21:39:42 -07002486 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490 // Make sure that composition can never be stalled by a virtual display
2491 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002492 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002493 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2495 }
2496
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 creationArgs.displayInstallOrientation =
2498 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002499
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002501 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Lloyd Pique90c115d2018-09-18 21:39:42 -07002503 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504
2505 if (maxFrameBufferAcquiredBuffers >= 3) {
2506 nativeWindowSurface->preallocateBuffers();
2507 }
2508
2509 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002510 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002511 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002513 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002515 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
Lloyd Piquef5275482019-01-29 18:42:42 -08002516 RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 if (!state.isVirtual()) {
2518 LOG_ALWAYS_FATAL_IF(!displayId);
2519 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002520 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 display->setLayerStack(state.layerStack);
2523 display->setProjection(state.orientation, state.viewport, state.frame);
2524 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002526 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527}
2528
Lloyd Pique347200f2017-12-14 17:00:15 -08002529void SurfaceFlinger::processDisplayChangesLocked() {
2530 // here we take advantage of Vector's copy-on-write semantics to
2531 // improve performance by skipping the transaction entirely when
2532 // know that the lists are identical
2533 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2534 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2535 if (!curr.isIdenticalTo(draw)) {
2536 mVisibleRegionsDirty = true;
2537 const size_t cc = curr.size();
2538 size_t dc = draw.size();
2539
2540 // find the displays that were removed
2541 // (ie: in drawing state but not in current state)
2542 // also handle displays that changed
2543 // (ie: displays that are in both lists)
2544 for (size_t i = 0; i < dc;) {
2545 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2546 if (j < 0) {
2547 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002548 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002549 // Save display ID before disconnecting.
2550 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002551 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002552
2553 if (!display->isVirtual()) {
2554 LOG_ALWAYS_FATAL_IF(!displayId);
2555 dispatchDisplayHotplugEvent(displayId->value, false);
2556 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002557 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002558
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002559 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002560 } else {
2561 // this display is in both lists. see if something changed.
2562 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2565 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2566 if (state_binder != draw_binder) {
2567 // changing the surface is like destroying and
2568 // recreating the DisplayDevice, so we just remove it
2569 // from the drawing state, so that it get re-added
2570 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002572 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002573 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002574 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002575 mDrawingState.displays.removeItemsAt(i);
2576 dc--;
2577 // at this point we must loop to the next item
2578 continue;
2579 }
2580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002581 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002582 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002583 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002584 }
2585 if ((state.orientation != draw[i].orientation) ||
2586 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002587 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002588 }
2589 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591 }
2592 }
2593 }
2594 ++i;
2595 }
2596
2597 // find displays that were added
2598 // (ie: in current state but not in drawing state)
2599 for (size_t i = 0; i < cc; i++) {
2600 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2601 const DisplayDeviceState& state(curr[i]);
2602
Lloyd Pique542307f2018-10-19 13:24:08 -07002603 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 sp<IGraphicBufferProducer> producer;
2605 sp<IGraphicBufferProducer> bqProducer;
2606 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002607 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002608
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002610 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 // Virtual displays without a surface are dormant:
2612 // they have external state (layer stack, projection,
2613 // etc.) but no internal state (i.e. a DisplayDevice).
2614 if (state.surface != nullptr) {
2615 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002617 int width = 0;
2618 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2619 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2620 int height = 0;
2621 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2622 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2623 int intFormat = 0;
2624 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2625 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002626 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002627
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 displayId =
2629 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002630 }
2631
2632 // TODO: Plumb requested format back up to consumer
2633
2634 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002636 bqProducer, bqConsumer,
2637 state.displayName);
2638
2639 dispSurface = vds;
2640 producer = vds;
2641 }
2642 } else {
2643 ALOGE_IF(state.surface != nullptr,
2644 "adding a supported display, but rendering "
2645 "surface is provided (%p), ignoring it",
2646 state.surface.get());
2647
Dominik Laskowski075d3172018-05-24 15:50:06 -07002648 displayId = state.displayId;
2649 LOG_ALWAYS_FATAL_IF(!displayId);
2650 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 producer = bqProducer;
2652 }
2653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002656 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002657 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002659 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002661 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002662 }
2663 }
2664 }
2665 }
2666 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002667
2668 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002669}
2670
Mathias Agopian87baae12012-07-31 12:38:26 -07002671void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002672{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002673 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2674
Dan Stoza7dde5992015-05-22 09:51:44 -07002675 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002676 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2677 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002678 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 /*
2681 * Traversal of the children
2682 * (perform the transaction for each of them if needed)
2683 */
2684
Marissa Wall06255332019-03-27 13:48:27 -07002685 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002686 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002688 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689
2690 const uint32_t flags = layer->doTransaction(0);
2691 if (flags & Layer::eVisibleRegion)
2692 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002693
2694 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002695 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002696 }
Robert Carr2047fae2016-11-28 14:09:09 -08002697 });
Marissa Wall06255332019-03-27 13:48:27 -07002698 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700
2701 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 */
2704
Mathias Agopiane57f2922012-08-09 16:29:12 -07002705 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002707 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002711 // The transform hint might have changed for some layers
2712 // (either because a display has changed, or because a layer
2713 // as changed).
2714 //
2715 // Walk through all the layers in currentLayers,
2716 // and update their transform hint.
2717 //
2718 // If a layer is visible only on a single display, then that
2719 // display is used to calculate the hint, otherwise we use the
2720 // default display.
2721 //
2722 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2723 // the hint is set before we acquire a buffer from the surface texture.
2724 //
2725 // NOTE: layer transactions have taken place already, so we use their
2726 // drawing state. However, SurfaceFlinger's own transaction has not
2727 // happened yet, so we must use the current state layer list
2728 // (soon to become the drawing state list).
2729 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002731 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002732 bool first = true;
2733 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002734 // NOTE: we rely on the fact that layers are sorted by
2735 // layerStack first (so we don't have to traverse the list
2736 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002738 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002739 currentlayerStack = layerStack;
2740 // figure out if this layerstack is mirrored
2741 // (more than one display) if so, pick the default display,
2742 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 hintDisplay = nullptr;
2744 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002745 if (display->getCompositionDisplay()
2746 ->belongsInOutput(layer->getLayerStack(),
2747 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 if (hintDisplay) {
2749 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002750 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002751 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002752 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002753 }
2754 }
2755 }
2756 }
Chet Haase91d25932013-04-11 15:24:55 -07002757
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002758 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002759 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2760 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002761
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002762 // could be null when this layer is using a layerStack
2763 // that is not visible on any display. Also can occur at
2764 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002765 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002766 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002767
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002769 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002770 if (hintDisplay) {
2771 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002772 }
Robert Carr2047fae2016-11-28 14:09:09 -08002773
2774 first = false;
2775 });
Mathias Agopian84300952012-11-21 16:02:13 -08002776 }
2777
2778
Mathias Agopian3559b072012-08-15 13:46:03 -07002779 /*
2780 * Perform our own transaction if needed
2781 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782
2783 if (mLayersAdded) {
2784 mLayersAdded = false;
2785 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002786 mVisibleRegionsDirty = true;
2787 }
2788
2789 // some layers might have been removed, so
2790 // we need to update the regions they're exposing.
2791 if (mLayersRemoved) {
2792 mLayersRemoved = false;
2793 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002794 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002796 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002798 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002799 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002800 }
Robert Carr2047fae2016-11-28 14:09:09 -08002801 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 }
2803
Vishnu Nairec0ab382019-02-13 15:32:56 -08002804 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002806}
2807
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002808void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002809 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002810 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002811 return;
2812 }
2813
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002814 if (mVisibleRegionsDirty || mInputInfoChanged) {
2815 mInputInfoChanged = false;
2816 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002817 } else if (mInputWindowCommands.syncInputWindows) {
2818 // If the caller requested to sync input windows, but there are no
2819 // changes to input windows, notify immediately.
2820 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002821 }
2822
2823 executeInputWindowCommands();
2824}
2825
2826void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002827 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002828
2829 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2830 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002831 // When calculating the screen bounds we ignore the transparent region since it may
2832 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002833 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002834 }
2835 });
chaviw291d88a2019-02-14 10:33:58 -08002836
2837 mInputFlinger->setInputWindows(inputHandles,
2838 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2839 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002840}
2841
Vishnu Nairec0ab382019-02-13 15:32:56 -08002842void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002843 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002844 mPendingInputWindowCommands.clear();
2845}
2846
chaviwfbe5d9c2018-12-26 12:23:37 -08002847void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002848 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2849 if (transferTouchFocusCommand.fromToken != nullptr &&
2850 transferTouchFocusCommand.toToken != nullptr &&
2851 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2852 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2853 transferTouchFocusCommand.toToken);
2854 }
2855 }
2856
2857 mInputWindowCommands.clear();
2858}
2859
Riley Andrews03414a12014-07-01 14:22:59 -07002860void SurfaceFlinger::updateCursorAsync()
2861{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002862 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002863 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002864 continue;
2865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2868 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002869 }
2870 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002871}
2872
2873void SurfaceFlinger::commitTransaction()
2874{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002875 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002876 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 for (const auto& l : mLayersPendingRemoval) {
2878 recordBufferingStats(l->getName().string(),
2879 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002880
Lloyd Pique07e33212018-12-18 16:33:37 -08002881 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002882 if (l->isRemovedFromCurrentState()) {
chaviw49a108c2019-08-12 11:23:06 -07002883 l->latchAndReleaseBuffer();
Robert Carr2e102c92018-10-23 12:11:15 -07002884 }
chaviw74d90ad2019-04-26 14:45:26 -07002885
2886 // If the layer has been removed and has no parent, then it will not be reachable
2887 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2888 // ensure we can copy its current to drawing state.
2889 if (!l->getParent()) {
2890 mOffscreenLayers.emplace(l.get());
2891 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 }
2893 mLayersPendingRemoval.clear();
2894 }
2895
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002896 // If this transaction is part of a window animation then the next frame
2897 // we composite should be considered an animation as well.
2898 mAnimCompositionPending = mAnimTransactionPending;
2899
Nataniel Borges2b796da2019-02-15 13:32:18 -08002900 withTracingLock([&]() {
2901 mDrawingState = mCurrentState;
2902 // clear the "changed" flags in current state
2903 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002904
chaviw74d90ad2019-04-26 14:45:26 -07002905 mDrawingState.traverseInZOrder([&](Layer* layer) {
2906 layer->commitChildList();
2907
2908 // If the layer can be reached when traversing mDrawingState, then the layer is no
2909 // longer offscreen. Remove the layer from the offscreenLayer set.
2910 if (mOffscreenLayers.count(layer)) {
2911 mOffscreenLayers.erase(layer);
2912 }
2913 });
2914
2915 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002917
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002918 mTransactionPending = false;
2919 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002920 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921}
2922
Nataniel Borges2b796da2019-02-15 13:32:18 -08002923void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2924 if (mTracingEnabledChanged) {
2925 mTracingEnabled = mTracing.isEnabled();
2926 mTracingEnabledChanged = false;
2927 }
2928
2929 // Synchronize with Tracing thread
2930 std::unique_lock<std::mutex> lock;
2931 if (mTracingEnabled) {
2932 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2933 }
2934
2935 lockedOperation();
2936
2937 // Synchronize with Tracing thread
2938 if (mTracingEnabled) {
2939 lock.unlock();
2940 }
2941}
2942
chaviw74d90ad2019-04-26 14:45:26 -07002943void SurfaceFlinger::commitOffscreenLayers() {
2944 for (Layer* offscreenLayer : mOffscreenLayers) {
2945 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2946 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2947 if (!trFlags) return;
2948
2949 layer->doTransaction(0);
2950 layer->commitChildList();
2951 });
2952 }
2953}
2954
Lloyd Pique32cbe282018-10-19 13:09:22 -07002955void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002956 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002957 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002958 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002959
Lloyd Pique32cbe282018-10-19 13:09:22 -07002960 auto display = displayDevice->getCompositionDisplay();
2961
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 Region aboveOpaqueLayers;
2963 Region aboveCoveredLayers;
2964 Region dirty;
2965
Mathias Agopian87baae12012-07-31 12:38:26 -07002966 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002969 // start with the whole surface at its current location
2970 const Layer::State& s(layer->getDrawingState());
2971
Jesse Hall01e29052013-02-19 16:13:35 -08002972 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08002973 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002974 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002976
Mathias Agopianab028732010-03-16 16:41:46 -07002977 /*
2978 * opaqueRegion: area of a surface that is fully opaque.
2979 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002981
2982 /*
2983 * visibleRegion: area of a surface that is visible on screen
2984 * and not fully transparent. This is essentially the layer's
2985 * footprint minus the opaque regions above it.
2986 * Areas covered by a translucent surface are considered visible.
2987 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002989
2990 /*
2991 * coveredRegion: area of a surface that is covered by all
2992 * visible regions above it (which includes the translucent areas).
2993 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002995
Jesse Halla8026d22012-09-25 13:25:04 -07002996 /*
2997 * transparentRegion: area of a surface that is hinted to be completely
2998 * transparent. This is only used to tell when the layer has no visible
2999 * non-transparent regions and can be removed from the layer list. It
3000 * does not affect the visibleRegion of this layer or any layers
3001 * beneath it. The hint may not be correct if apps don't respect the
3002 * SurfaceView restrictions (which, sadly, some don't).
3003 */
3004 Region transparentRegion;
3005
Mathias Agopianab028732010-03-16 16:41:46 -07003006
3007 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003008 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003009 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003010 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003011
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003013 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003014 if (!visibleRegion.isEmpty()) {
3015 // Remove the transparent area from the visible region
3016 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003017 if (tr.preserveRects()) {
3018 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003019 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003020 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003021 // transformation too complex, can't do the
3022 // transparent region optimization.
3023 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 }
Mathias Agopianab028732010-03-16 16:41:46 -07003025 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003026
Mathias Agopianab028732010-03-16 16:41:46 -07003027 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003028 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003029 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003030 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003031 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003032 // the opaque region is the layer's footprint
3033 opaqueRegion = visibleRegion;
3034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 }
3036 }
3037
Robert Carre5f4f692018-01-12 13:12:28 -08003038 if (visibleRegion.isEmpty()) {
3039 layer->clearVisibilityRegions();
3040 return;
3041 }
3042
Mathias Agopianab028732010-03-16 16:41:46 -07003043 // Clip the covered region to the visible region
3044 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3045
3046 // Update aboveCoveredLayers for next (lower) layer
3047 aboveCoveredLayers.orSelf(visibleRegion);
3048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 // subtract the opaque region covered by the layers above us
3050 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051
3052 // compute this layer's dirty region
3053 if (layer->contentDirty) {
3054 // we need to invalidate the whole region
3055 dirty = visibleRegion;
3056 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 layer->contentDirty = false;
3059 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003060 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003061 * the exposed region consists of two components:
3062 * 1) what's VISIBLE now and was COVERED before
3063 * 2) what's EXPOSED now less what was EXPOSED before
3064 *
3065 * note that (1) is conservative, we start with the whole
3066 * visible region but only keep what used to be covered by
3067 * something -- which mean it may have been exposed.
3068 *
3069 * (2) handles areas that were not covered by anything but got
3070 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003071 */
Mathias Agopianab028732010-03-16 16:41:46 -07003072 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003073 const Region oldVisibleRegion = layer->visibleRegion;
3074 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3076 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 }
3078 dirty.subtractSelf(aboveOpaqueLayers);
3079
3080 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003081 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082
Mathias Agopianab028732010-03-16 16:41:46 -07003083 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003085
Jesse Halla8026d22012-09-25 13:25:04 -07003086 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 layer->setVisibleRegion(visibleRegion);
3088 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003089 layer->setVisibleNonTransparentRegion(
3090 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003091 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092
Mathias Agopian87baae12012-07-31 12:38:26 -07003093 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094}
3095
Chia-I Wuab0c3192017-08-01 11:29:00 -07003096void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003097 for (const auto& [token, displayDevice] : mDisplays) {
3098 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003099 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003100 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003101 }
3102 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003103}
3104
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106{
Ady Abraham09bd3922019-04-08 10:44:56 -07003107 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 ALOGV("handlePageFlip");
3109
Brian Andersond6927fb2016-07-23 23:37:30 -07003110 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111
Mathias Agopian4fec8732012-06-29 14:12:52 -07003112 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003114 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003115
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003116 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3117
Eric Penner51c59cd2014-07-28 19:51:58 -07003118 // Store the set of layers that need updates. This set must not change as
3119 // buffers are being latched, as this could result in a deadlock.
3120 // Example: Two producers share the same command stream and:
3121 // 1.) Layer 0 is latched
3122 // 2.) Layer 0 gets a new frame
3123 // 2.) Layer 1 gets a new frame
3124 // 3.) Layer 1 is latched.
3125 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3126 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003127 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003128 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003129 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003130 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003131 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003132 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003133 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003134 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003135 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003136 } else {
3137 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003138 }
Robert Carr2047fae2016-11-28 14:09:09 -08003139 });
3140
chaviw49a108c2019-08-12 11:23:06 -07003141 // The client can continue submitting buffers for offscreen layers, but they will not
3142 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3143 // layers to ensure dequeueBuffer doesn't block indefinitely.
3144 for (Layer* offscreenLayer : mOffscreenLayers) {
3145 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
3146 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3147 }
3148
Lloyd Piquef2c79392018-12-20 16:23:33 -08003149 if (!mLayersWithQueuedFrames.empty()) {
3150 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3151 // writes to Layer current state. See also b/119481871
3152 Mutex::Autolock lock(mStateLock);
3153
3154 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003155 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003156 mLayersPendingRefresh.push_back(layer);
3157 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003158 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003159 if (layer->isBufferLatched()) {
3160 newDataLatched = true;
3161 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003162 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003163 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003164
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003165 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003166
3167 // If we will need to wake up at some time in the future to deal with a
3168 // queued frame that shouldn't be displayed during this vsync period, wake
3169 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003170 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003171 signalLayerUpdate();
3172 }
3173
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003174 // enter boot animation on first buffer latch
3175 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3176 ALOGI("Enter boot animation");
3177 mBootStage = BootStage::BOOTANIMATION;
3178 }
3179
Dan Stoza6b9454d2014-11-07 16:00:59 -08003180 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003181 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182}
3183
Mathias Agopianad456f92011-01-13 17:53:01 -08003184void SurfaceFlinger::invalidateHwcGeometry()
3185{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003186 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003187}
3188
Lloyd Pique32cbe282018-10-19 13:09:22 -07003189void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003190 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003191 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003192 // We only need to actually compose the display if:
3193 // 1) It is being handled by hardware composer, which may need this to
3194 // keep its virtual display state machine in sync, or
3195 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003196 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003198 return;
3199 }
3200
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003202 base::unique_fd readyFence;
Lloyd Pique688abd42019-02-15 15:42:24 -08003203 if (!display->composeSurfaces(Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003204
3205 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003206 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Robert Carrc0df3122019-04-11 13:18:21 -07003209status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3210 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3211 const sp<IBinder>& parentHandle,
3212 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003213 // add this layer to the current state list
3214 {
3215 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003216 sp<Layer> parent;
3217 if (parentHandle != nullptr) {
3218 parent = fromHandle(parentHandle);
3219 if (parent == nullptr) {
3220 return NAME_NOT_FOUND;
3221 }
3222 } else {
3223 parent = parentLayer;
3224 }
3225
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003227 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003228 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003229 return NO_MEMORY;
3230 }
Robert Carrc0df3122019-04-11 13:18:21 -07003231
3232 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3233
Robert Carrb89ea9d2018-12-10 13:01:14 -08003234 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003235 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003236 } else if (parent == nullptr) {
3237 lbc->onRemovedFromCurrentState();
3238 } else if (parent->isRemovedFromCurrentState()) {
3239 parent->addChild(lbc);
3240 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003241 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003242 parent->addChild(lbc);
3243 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003244
Yiwei Zhang243b3782018-05-15 17:40:04 -07003245 if (gbc != nullptr) {
3246 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3247 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3248 mMaxGraphicBufferProducerListSize,
3249 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3250 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003251 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003252 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003253 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003254 }
3255
Mathias Agopian96f08192010-06-02 23:28:45 -07003256 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003257 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003258
Dan Stoza7d89d062015-04-30 13:29:25 -07003259 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003260}
3261
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003262uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003263 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003264}
3265
Mathias Agopian3f844832013-08-07 21:24:32 -07003266uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003267 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268}
3269
Mathias Agopian3f844832013-08-07 21:24:32 -07003270uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003271 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003272}
3273
3274uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003275 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003276 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003277 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003279 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 }
3281 return old;
3282}
3283
Marissa Wall713b63f2018-10-17 15:42:43 -07003284bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003285 // to prevent onHandleDestroyed from being called while the lock is held,
3286 // we must keep a copy of the transactions (specifically the composer
3287 // states) around outside the scope of the lock
3288 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003289 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003290 {
3291 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003292
Valerie Haufce31b82019-04-30 16:41:14 -07003293 auto it = mTransactionQueues.begin();
3294 while (it != mTransactionQueues.end()) {
3295 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003296
Valerie Haufce31b82019-04-30 16:41:14 -07003297 while (!transactionQueue.empty()) {
3298 const auto& transaction = transactionQueue.front();
3299 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003300 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003301 transaction.states)) {
3302 setTransactionFlags(eTransactionFlushNeeded);
3303 break;
3304 }
3305 transactions.push_back(transaction);
3306 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3307 mPendingInputWindowCommands, transaction.desiredPresentTime,
3308 transaction.buffer, transaction.callback,
3309 transaction.postTime, transaction.privileged,
3310 /*isMainThread*/ true);
3311 transactionQueue.pop();
3312 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003313 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003314
Valerie Haufce31b82019-04-30 16:41:14 -07003315 if (transactionQueue.empty()) {
3316 it = mTransactionQueues.erase(it);
3317 mTransactionCV.broadcast();
3318 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003319 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003320 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003321 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003322 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003323 return flushedATransaction;
3324}
3325
3326bool SurfaceFlinger::transactionFlushNeeded() {
3327 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003328}
3329
chaviwca27f252018-02-06 16:46:39 -08003330
Marissa Wall17b4e452018-12-26 16:32:34 -08003331bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003332 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003333 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003334 if (!useCachedExpectedPresentTime)
3335 populateExpectedPresentTime();
3336
3337 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003338 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3339 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3340 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3341 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3342 return false;
3343 }
3344
Marissa Wall713b63f2018-10-17 15:42:43 -07003345 for (const ComposerState& state : states) {
3346 const layer_state_t& s = state.state;
3347 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3348 continue;
3349 }
3350 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003351 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003352 }
3353 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003354 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003355}
3356
3357void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3358 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003359 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003360 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003361 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003362 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003363 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003364 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003365
Valerie Haubc6ddb12019-03-08 11:10:15 -08003366 const int64_t postTime = systemTime();
3367
Robert Carr14167e02019-02-13 13:50:55 -08003368 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3369
Mathias Agopian698c0872011-06-28 19:09:31 -07003370 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371
Marissa Wall713b63f2018-10-17 15:42:43 -07003372 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003373 auto itr = mTransactionQueues.find(applyToken);
3374 // if this is an animation frame, wait until prior animation frame has
3375 // been applied by SF
3376 if (flags & eAnimation) {
3377 while (itr != mTransactionQueues.end()) {
3378 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3379 if (CC_UNLIKELY(err != NO_ERROR)) {
3380 ALOGW_IF(err == TIMED_OUT,
3381 "setTransactionState timed out "
3382 "waiting for animation frame to apply");
3383 break;
3384 }
3385 itr = mTransactionQueues.find(applyToken);
3386 }
3387 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003388
3389 // Expected present time is computed and cached on invalidate, so it may be stale.
3390 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3391 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003392 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003393 uncacheBuffer, listenerCallbacks, postTime,
3394 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003395 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003396 return;
3397 }
3398
Valerie Haubc6ddb12019-03-08 11:10:15 -08003399 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003400 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003401}
3402
3403void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003404 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003405 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003406 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003407 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003408 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003409 const int64_t postTime, bool privileged,
3410 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003411 uint32_t transactionFlags = 0;
3412
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003413 if (flags & eAnimation) {
3414 // For window updates that are part of an animation we must wait for
3415 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003416 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003417 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003418 if (CC_UNLIKELY(err != NO_ERROR)) {
3419 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003420 // caller after a few seconds.
3421 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3422 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003423 mAnimTransactionPending = false;
3424 break;
3425 }
3426 }
3427 }
3428
chaviwca27f252018-02-06 16:46:39 -08003429 for (const DisplayState& display : displays) {
3430 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003431 }
3432
Marissa Walld600d572019-03-26 15:38:50 -07003433 // In case the client has sent a Transaction that should receive callbacks but without any
3434 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3435 // to the callback thread so it can send an empty callback
3436 if (!listenerCallbacks.empty()) {
3437 mTransactionCompletedThread.run();
3438 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003439 for (const auto& listenerCallback : listenerCallbacks) {
3440 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003441 }
3442
Marissa Walle2ffb422018-10-12 11:33:52 -07003443 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003444 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003445 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3446 postTime, privileged);
3447 }
3448
Marissa Wallefb71af2019-06-27 14:45:53 -07003449 for (const auto& listenerCallback : listenerCallbacks) {
3450 mTransactionCompletedThread.endRegistration(listenerCallback);
3451 }
3452
Marissa Walle2ffb422018-10-12 11:33:52 -07003453 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003454 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003455 mTransactionCompletedThread.sendCallbacks();
3456 }
3457 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003458
chaviw273171b2018-12-26 11:46:30 -08003459 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3460
Marissa Wall947d34e2019-03-29 14:03:53 -07003461 if (uncacheBuffer.isValid()) {
3462 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003463 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003464 }
3465
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003466 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3467 // anyway. This can be used as a flush mechanism for previous async transactions.
3468 // Empty animation transaction can be used to simulate back-pressure, so also force a
3469 // transaction for empty animation transactions.
3470 if (transactionFlags == 0 &&
3471 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003472 transactionFlags = eTransactionNeeded;
3473 }
3474
Marissa Wall06255332019-03-27 13:48:27 -07003475 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3476 // so we don't have to wake up again next frame to preform an uneeded traversal.
3477 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3478 transactionFlags = transactionFlags & (~eTraversalNeeded);
3479 mTraversalNeededMainThread = true;
3480 }
3481
Mathias Agopian386aa982011-11-07 21:58:03 -08003482 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003483 if (mInterceptor->isEnabled()) {
3484 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003485 }
Irvel468051e2016-06-13 16:44:44 -07003486
Mathias Agopian386aa982011-11-07 21:58:03 -08003487 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003488 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3489 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003490 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003491
3492 // if this is a synchronous transaction, wait for it to take effect
3493 // before returning.
3494 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003495 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003496 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003497 if (flags & eAnimation) {
3498 mAnimTransactionPending = true;
3499 }
chaviw4fe36852019-04-15 16:25:49 -07003500 if (mPendingInputWindowCommands.syncInputWindows) {
3501 mPendingSyncInputWindows = true;
3502 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003503
3504 // applyTransactionState can be called by either the main SF thread or by
3505 // another process through setTransactionState. While a given process may wish
3506 // to wait on synchronous transactions, the main SF thread should never
3507 // be blocked. Therefore, we only wait if isMainThread is false.
3508 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003509 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3510 if (CC_UNLIKELY(err != NO_ERROR)) {
3511 // just in case something goes wrong in SF, return to the
3512 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003513 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3514 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003515 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003516 break;
3517 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
3520}
3521
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003522uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3523 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3524 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003525
Mathias Agopiane57f2922012-08-09 16:29:12 -07003526 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003527 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3528
3529 const uint32_t what = s.what;
3530 if (what & DisplayState::eSurfaceChanged) {
3531 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3532 state.surface = s.surface;
3533 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003534 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003535 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003536 if (what & DisplayState::eLayerStackChanged) {
3537 if (state.layerStack != s.layerStack) {
3538 state.layerStack = s.layerStack;
3539 flags |= eDisplayTransactionNeeded;
3540 }
3541 }
3542 if (what & DisplayState::eDisplayProjectionChanged) {
3543 if (state.orientation != s.orientation) {
3544 state.orientation = s.orientation;
3545 flags |= eDisplayTransactionNeeded;
3546 }
3547 if (state.frame != s.frame) {
3548 state.frame = s.frame;
3549 flags |= eDisplayTransactionNeeded;
3550 }
3551 if (state.viewport != s.viewport) {
3552 state.viewport = s.viewport;
3553 flags |= eDisplayTransactionNeeded;
3554 }
3555 }
3556 if (what & DisplayState::eDisplaySizeChanged) {
3557 if (state.width != s.width) {
3558 state.width = s.width;
3559 flags |= eDisplayTransactionNeeded;
3560 }
3561 if (state.height != s.height) {
3562 state.height = s.height;
3563 flags |= eDisplayTransactionNeeded;
3564 }
3565 }
3566
Mathias Agopiane57f2922012-08-09 16:29:12 -07003567 return flags;
3568}
3569
Robert Carr14167e02019-02-13 13:50:55 -08003570bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003571 IPCThreadState* ipc = IPCThreadState::self();
3572 const int pid = ipc->getCallingPid();
3573 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003574 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003575 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003576 return false;
3577 }
3578 return true;
3579}
3580
Marissa Wall3dad52d2019-03-22 14:03:19 -07003581uint32_t SurfaceFlinger::setClientStateLocked(
3582 const ComposerState& composerState, int64_t desiredPresentTime,
3583 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3584 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003585 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003586
Vishnu Nairf03652d2019-07-16 17:56:56 -07003587 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003588 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003589 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003590 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003591 new CallbackHandle(listenerCallback.transactionCompletedListener,
3592 listenerCallback.callbackIds, s.surface));
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 return 0;
3595 }
3596
chaviw8b3871a2017-11-01 17:41:01 -07003597 uint32_t flags = 0;
3598
Garfield Tan8a3083e2018-12-03 13:21:07 -08003599 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003600 bool geometryAppliesWithResize =
3601 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003602
3603 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3604 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003605 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003606 layer->pushPendingState();
3607 }
3608
chaviw8b3871a2017-11-01 17:41:01 -07003609 if (what & layer_state_t::ePositionChanged) {
3610 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3611 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003612 }
chaviw8b3871a2017-11-01 17:41:01 -07003613 }
3614 if (what & layer_state_t::eLayerChanged) {
3615 // NOTE: index needs to be calculated before we update the state
3616 const auto& p = layer->getParent();
3617 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003618 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003619 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003620 mCurrentState.layersSortedByZ.removeAt(idx);
3621 mCurrentState.layersSortedByZ.add(layer);
3622 // we need traversal (state changed)
3623 // AND transaction (list changed)
3624 flags |= eTransactionNeeded|eTraversalNeeded;
3625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 } else {
3627 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003628 flags |= eTransactionNeeded|eTraversalNeeded;
3629 }
3630 }
chaviw8b3871a2017-11-01 17:41:01 -07003631 }
3632 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003633 // NOTE: index needs to be calculated before we update the state
3634 const auto& p = layer->getParent();
3635 if (p == nullptr) {
3636 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3637 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3638 mCurrentState.layersSortedByZ.removeAt(idx);
3639 mCurrentState.layersSortedByZ.add(layer);
3640 // we need traversal (state changed)
3641 // AND transaction (list changed)
3642 flags |= eTransactionNeeded|eTraversalNeeded;
3643 }
3644 } else {
3645 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3646 flags |= eTransactionNeeded|eTraversalNeeded;
3647 }
chaviw8b3871a2017-11-01 17:41:01 -07003648 }
3649 }
3650 if (what & layer_state_t::eSizeChanged) {
3651 if (layer->setSize(s.w, s.h)) {
3652 flags |= eTraversalNeeded;
3653 }
3654 }
3655 if (what & layer_state_t::eAlphaChanged) {
3656 if (layer->setAlpha(s.alpha))
3657 flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eColorChanged) {
3660 if (layer->setColor(s.color))
3661 flags |= eTraversalNeeded;
3662 }
Peiyong Lind3788632018-09-18 16:01:31 -07003663 if (what & layer_state_t::eColorTransformChanged) {
3664 if (layer->setColorTransform(s.colorTransform)) {
3665 flags |= eTraversalNeeded;
3666 }
3667 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003668 if (what & layer_state_t::eBackgroundColorChanged) {
3669 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3670 flags |= eTraversalNeeded;
3671 }
3672 }
chaviw8b3871a2017-11-01 17:41:01 -07003673 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003674 // TODO: b/109894387
3675 //
3676 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3677 // rotation. To see the problem observe that if we have a square parent, and a child
3678 // of the same size, then we rotate the child 45 degrees around it's center, the child
3679 // must now be cropped to a non rectangular 8 sided region.
3680 //
3681 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3682 // private API, and the WindowManager only uses rotation in one case, which is on a top
3683 // level layer in which cropping is not an issue.
3684 //
3685 // However given that abuse of rotation matrices could lead to surfaces extending outside
3686 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3687 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3688 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003689 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003690 flags |= eTraversalNeeded;
3691 }
3692 if (what & layer_state_t::eTransparentRegionChanged) {
3693 if (layer->setTransparentRegionHint(s.transparentRegion))
3694 flags |= eTraversalNeeded;
3695 }
3696 if (what & layer_state_t::eFlagsChanged) {
3697 if (layer->setFlags(s.flags, s.mask))
3698 flags |= eTraversalNeeded;
3699 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003700 if (what & layer_state_t::eCropChanged_legacy) {
3701 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003702 flags |= eTraversalNeeded;
3703 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003704 if (what & layer_state_t::eCornerRadiusChanged) {
3705 if (layer->setCornerRadius(s.cornerRadius))
3706 flags |= eTraversalNeeded;
3707 }
chaviw8b3871a2017-11-01 17:41:01 -07003708 if (what & layer_state_t::eLayerStackChanged) {
3709 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3710 // We only allow setting layer stacks for top level layers,
3711 // everything else inherits layer stack from its parent.
3712 if (layer->hasParent()) {
3713 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3714 layer->getName().string());
3715 } else if (idx < 0) {
3716 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3717 "that also does not appear in the top level layer list. Something"
3718 " has gone wrong.", layer->getName().string());
3719 } else if (layer->setLayerStack(s.layerStack)) {
3720 mCurrentState.layersSortedByZ.removeAt(idx);
3721 mCurrentState.layersSortedByZ.add(layer);
3722 // we need traversal (state changed)
3723 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003724 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003725 }
3726 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003727 if (what & layer_state_t::eDeferTransaction_legacy) {
3728 if (s.barrierHandle_legacy != nullptr) {
3729 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3730 } else if (s.barrierGbp_legacy != nullptr) {
3731 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003732 if (authenticateSurfaceTextureLocked(gbp)) {
3733 const auto& otherLayer =
3734 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003735 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003736 } else {
3737 ALOGE("Attempt to defer transaction to to an"
3738 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003739 }
3740 }
chaviw8b3871a2017-11-01 17:41:01 -07003741 // We don't trigger a traversal here because if no other state is
3742 // changed, we don't want this to cause any more work
3743 }
chaviw8b3871a2017-11-01 17:41:01 -07003744 if (what & layer_state_t::eReparentChildren) {
3745 if (layer->reparentChildren(s.reparentHandle)) {
3746 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003747 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003748 }
chaviw8b3871a2017-11-01 17:41:01 -07003749 if (what & layer_state_t::eDetachChildren) {
3750 layer->detachChildren();
3751 }
3752 if (what & layer_state_t::eOverrideScalingModeChanged) {
3753 layer->setOverrideScalingMode(s.overrideScalingMode);
3754 // We don't trigger a traversal here because if no other state is
3755 // changed, we don't want this to cause any more work
3756 }
Marissa Wall61c58622018-07-18 10:12:20 -07003757 if (what & layer_state_t::eTransformChanged) {
3758 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3759 }
3760 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3761 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3762 flags |= eTraversalNeeded;
3763 }
3764 if (what & layer_state_t::eCropChanged) {
3765 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3766 }
Marissa Wall861616d2018-10-22 12:52:23 -07003767 if (what & layer_state_t::eFrameChanged) {
3768 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3769 }
Marissa Wall61c58622018-07-18 10:12:20 -07003770 if (what & layer_state_t::eAcquireFenceChanged) {
3771 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3772 }
3773 if (what & layer_state_t::eDataspaceChanged) {
3774 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3775 }
3776 if (what & layer_state_t::eHdrMetadataChanged) {
3777 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3778 }
3779 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3780 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3781 }
3782 if (what & layer_state_t::eApiChanged) {
3783 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3784 }
3785 if (what & layer_state_t::eSidebandStreamChanged) {
3786 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3787 }
Robert Carr720e5062018-07-30 17:45:14 -07003788 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003789 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003790 layer->setInputInfo(s.inputInfo);
3791 flags |= eTraversalNeeded;
3792 } else {
3793 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3794 }
Robert Carr720e5062018-07-30 17:45:14 -07003795 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003796 if (what & layer_state_t::eMetadataChanged) {
3797 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3798 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003799 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3800 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3801 flags |= eTraversalNeeded;
3802 }
3803 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003804 // This has to happen after we reparent children because when we reparent to null we remove
3805 // child layers from current state and remove its relative z. If the children are reparented in
3806 // the same transaction, then we have to make sure we reparent the children first so we do not
3807 // lose its relative z order.
3808 if (what & layer_state_t::eReparent) {
3809 bool hadParent = layer->hasParent();
3810 if (layer->reparent(s.parentHandleForChild)) {
3811 if (!hadParent) {
3812 mCurrentState.layersSortedByZ.remove(layer);
3813 }
3814 flags |= eTransactionNeeded | eTraversalNeeded;
3815 }
3816 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003817 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07003818 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003819 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003820 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3821 }
3822 }
Marissa Wall78b72202019-03-15 14:58:34 -07003823 bool bufferChanged = what & layer_state_t::eBufferChanged;
3824 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3825 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003826 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003827 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003828 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3829 if (success) {
3830 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3831 success = ClientCache::getInstance()
3832 .registerErasedRecipient(s.cachedBuffer,
3833 wp<ClientCache::ErasedRecipient>(this));
3834 if (!success) {
3835 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3836 }
3837 }
Marissa Wall78b72202019-03-15 14:58:34 -07003838 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003839 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003840 } else if (bufferChanged) {
3841 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003842 }
Marissa Wall78b72202019-03-15 14:58:34 -07003843 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003844 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003845 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003846 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003847 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003848 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3849 // Do not put anything that updates layer state or modifies flags after
3850 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003851 return flags;
3852}
3853
chaviw273171b2018-12-26 11:46:30 -08003854uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3855 uint32_t flags = 0;
3856 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3857 flags |= eTraversalNeeded;
3858 }
3859
chaviwa911b102019-02-14 10:18:33 -08003860 if (inputWindowCommands.syncInputWindows) {
3861 flags |= eTraversalNeeded;
3862 }
3863
Vishnu Nairec0ab382019-02-13 15:32:56 -08003864 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003865 return flags;
3866}
3867
Marissa Wall2d814fb2019-04-09 18:52:57 +00003868status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3869 uint32_t h, PixelFormat format, uint32_t flags,
3870 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003871 sp<IGraphicBufferProducer>* gbp,
3872 const sp<IBinder>& parentHandle,
3873 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003874 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003875 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003876 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003877 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003878 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003879
Robert Carrc0df3122019-04-11 13:18:21 -07003880 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3881 "Expected only one of parentLayer or parentHandle to be non-null. "
3882 "Programmer error?");
3883
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003884 status_t result = NO_ERROR;
3885
3886 sp<Layer> layer;
3887
Cody Northropbc755282017-03-31 12:00:08 -06003888 String8 uniqueName = getUniqueLayerName(name);
3889
Evan Roskya1f1e152019-01-24 16:17:46 -08003890 bool primaryDisplayOnly = false;
3891
3892 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3893 // TODO b/64227542
3894 if (metadata.has(METADATA_WINDOW_TYPE)) {
3895 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3896 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003897 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003898 primaryDisplayOnly = true;
3899 }
3900 }
3901
Mathias Agopian3165cc22012-08-08 19:42:09 -07003902 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003903 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003904 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3905 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003906
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003908 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003909 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3910 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003911 break;
chaviw13fdc492017-06-27 12:40:18 -07003912 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003913 // check if buffer size is set for color layer.
3914 if (w > 0 || h > 0) {
3915 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3916 int(w), int(h));
3917 return BAD_VALUE;
3918 }
3919
Evan Roskya1f1e152019-01-24 16:17:46 -08003920 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3921 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003922 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003923 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003924 // check if buffer size is set for container layer.
3925 if (w > 0 || h > 0) {
3926 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3927 int(w), int(h));
3928 return BAD_VALUE;
3929 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003930 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3931 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003932 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003933 default:
3934 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935 break;
3936 }
3937
Dan Stoza7d89d062015-04-30 13:29:25 -07003938 if (result != NO_ERROR) {
3939 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003940 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003941
Evan Roskya1f1e152019-01-24 16:17:46 -08003942 if (primaryDisplayOnly) {
3943 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003944 }
3945
Robert Carrb89ea9d2018-12-10 13:01:14 -08003946 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003947 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3948 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003949 if (result != NO_ERROR) {
3950 return result;
3951 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003952 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003953
3954 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003955 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956}
3957
Cody Northropbc755282017-03-31 12:00:08 -06003958String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3959{
3960 bool matchFound = true;
3961 uint32_t dupeCounter = 0;
3962
3963 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3964 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3965
Dan Stoza436ccf32018-06-21 12:10:12 -07003966 // Grab the state lock since we're accessing mCurrentState
3967 Mutex::Autolock lock(mStateLock);
3968
Cody Northropbc755282017-03-31 12:00:08 -06003969 // Loop over layers until we're sure there is no matching name
3970 while (matchFound) {
3971 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003972 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003973 if (layer->getName() == uniqueName) {
3974 matchFound = true;
3975 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3976 }
3977 });
3978 }
3979
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003980 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3981 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003982
3983 return uniqueName;
3984}
3985
Marissa Wallfd668622018-05-10 10:21:13 -07003986status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3987 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003988 LayerMetadata metadata, PixelFormat& format,
3989 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003990 sp<IGraphicBufferProducer>* gbp,
3991 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003993 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 case PIXEL_FORMAT_TRANSPARENT:
3995 case PIXEL_FORMAT_TRANSLUCENT:
3996 format = PIXEL_FORMAT_RGBA_8888;
3997 break;
3998 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003999 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 break;
4001 }
4002
Evan Roskya1f1e152019-01-24 16:17:46 -08004003 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4004 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004005 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004007 *handle = layer->getHandle();
4008 *gbp = layer->getProducer();
4009 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011
Marissa Wallfd668622018-05-10 10:21:13 -07004012 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004013 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014}
4015
Marissa Wall61c58622018-07-18 10:12:20 -07004016status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4017 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004018 LayerMetadata metadata, sp<IBinder>* handle,
4019 sp<Layer>* outLayer) {
4020 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4021 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004022 *handle = layer->getHandle();
4023 *outLayer = layer;
4024
4025 return NO_ERROR;
4026}
4027
Evan Roskya1f1e152019-01-24 16:17:46 -08004028status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4029 uint32_t h, uint32_t flags, LayerMetadata metadata,
4030 sp<IBinder>* handle, sp<Layer>* outLayer) {
4031 *outLayer = getFactory().createColorLayer(
4032 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004033 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004034 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004035}
4036
Evan Roskya1f1e152019-01-24 16:17:46 -08004037status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4038 uint32_t w, uint32_t h, uint32_t flags,
4039 LayerMetadata metadata, sp<IBinder>* handle,
4040 sp<Layer>* outLayer) {
4041 *outLayer = getFactory().createContainerLayer(
4042 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004043 *handle = (*outLayer)->getHandle();
4044 return NO_ERROR;
4045}
4046
4047
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004048void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004049 mLayersPendingRemoval.add(layer);
4050 mLayersRemoved = true;
4051 setTransactionFlags(eTransactionNeeded);
4052}
4053
Robert Carr695d5282018-12-18 15:27:58 -08004054void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004055{
Robert Carr2e102c92018-10-23 12:11:15 -07004056 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004057 // If a layer has a parent, we allow it to out-live it's handle
4058 // with the idea that the parent holds a reference and will eventually
4059 // be cleaned up. However no one cleans up the top-level so we do so
4060 // here.
4061 if (layer->getParent() == nullptr) {
4062 mCurrentState.layersSortedByZ.remove(layer);
4063 }
4064 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004065
4066 auto it = mLayersByLocalBinderToken.begin();
4067 while (it != mLayersByLocalBinderToken.end()) {
4068 if (it->second == layer) {
4069 it = mLayersByLocalBinderToken.erase(it);
4070 } else {
4071 it++;
4072 }
4073 }
4074
Robert Carr695d5282018-12-18 15:27:58 -08004075 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004076}
4077
Mathias Agopianb60314a2012-04-10 22:09:54 -07004078// ---------------------------------------------------------------------------
4079
Andy McFadden13a082e2012-08-24 10:16:42 -07004080void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004081 const auto display = getDefaultDisplayDeviceLocked();
4082 if (!display) return;
4083
4084 const sp<IBinder> token = display->getDisplayToken().promote();
4085 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004086
Jesse Hall01e29052013-02-19 16:13:35 -08004087 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004088 Vector<ComposerState> state;
4089 Vector<DisplayState> displays;
4090 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004091 d.what = DisplayState::eDisplayProjectionChanged |
4092 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004093 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004094 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004095 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004096 d.frame.makeInvalid();
4097 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004098 d.width = 0;
4099 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004100 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004101 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004102
Dominik Laskowskie9774092018-12-11 10:04:24 -08004103 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004104
Dominik Laskowski83b88212018-12-11 13:34:06 -08004105 const nsecs_t vsyncPeriod = getVsyncPeriod();
4106 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004107
Brian Andersond0010582017-03-07 13:20:31 -08004108 // Use phase of 0 since phase is not known.
4109 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004110 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004111 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004112}
4113
4114void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004115 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004116 postMessageAsync(
4117 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004118}
4119
Ady Abraham27c70212019-06-11 10:52:26 -07004120void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4121 if (mHWCVsyncState != enabled) {
4122 getHwComposer().setVsyncEnabled(displayId, enabled);
4123 mHWCVsyncState = enabled;
4124 }
4125}
4126
Dominik Laskowskie9774092018-12-11 10:04:24 -08004127void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004128 if (display->isVirtual()) {
4129 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004130 return;
4131 }
4132
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 const auto displayId = display->getId();
4134 LOG_ALWAYS_FATAL_IF(!displayId);
4135
Dominik Laskowski34157762018-10-31 13:07:19 -07004136 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004137
4138 int currentMode = display->getPowerMode();
4139 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004140 return;
4141 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004143 display->setPowerMode(mode);
4144
Lloyd Pique4dccc412018-01-22 17:21:36 -08004145 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004146 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004147 }
4148
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004149 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004150 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004151 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004152 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004153 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004154 mScheduler->onScreenAcquired(mAppConnectionHandle);
4155 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004158 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004159 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004160 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004161
4162 struct sched_param param = {0};
4163 param.sched_priority = 1;
4164 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4165 ALOGW("Couldn't set SCHED_FIFO on display on");
4166 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004167 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004168 // Turn off the display
4169 struct sched_param param = {0};
4170 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4171 ALOGW("Couldn't set SCHED_OTHER on display off");
4172 }
4173
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004174 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004175 mScheduler->disableHardwareVsync(true);
4176 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004177 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004178
Ady Abraham27c70212019-06-11 10:52:26 -07004179 // Make sure HWVsync is disabled before turning off the display
4180 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4181
Dominik Laskowski075d3172018-05-24 15:50:06 -07004182 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004183 mVisibleRegionsDirty = true;
4184 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004185 } else if (mode == HWC_POWER_MODE_DOZE ||
4186 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004187 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004188 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004189 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004190 mScheduler->onScreenAcquired(mAppConnectionHandle);
4191 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004192 }
4193 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4194 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004196 mScheduler->disableHardwareVsync(true);
4197 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004198 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004199 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004200 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004201 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004203 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004204
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004205 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004206 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004207 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004208 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004209 }
4210
Dominik Laskowski34157762018-10-31 13:07:19 -07004211 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004212}
4213
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004214void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004216 const auto display = getDisplayDevice(displayToken);
4217 if (!display) {
4218 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4219 displayToken.get());
4220 } else if (display->isVirtual()) {
4221 ALOGW("Attempt to set power mode %d for virtual display", mode);
4222 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004223 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004224 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004225 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004226}
4227
4228// ---------------------------------------------------------------------------
4229
Dominik Laskowskic2867142019-01-21 11:33:38 -08004230status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4231 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004233
Mathias Agopianbd115332013-04-18 16:41:04 -07004234 IPCThreadState* ipc = IPCThreadState::self();
4235 const int pid = ipc->getCallingPid();
4236 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004237
Mathias Agopianbd115332013-04-18 16:41:04 -07004238 if ((uid != AID_SHELL) &&
4239 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004240 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4241 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004242 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004243 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004244 // (this would indicate SF is stuck, but we want to be able to
4245 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004246 status_t err = mStateLock.timedLock(s2ns(1));
4247 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004248 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249 StringAppendF(&result,
4250 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4251 "(no locks held)\n",
4252 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004253 }
4254
Dominik Laskowskic2867142019-01-21 11:33:38 -08004255 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004256
Dominik Laskowskic2867142019-01-21 11:33:38 -08004257 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004258 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004259 {"--dispsync"s,
4260 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004261 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4262 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4263 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4264 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4265 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4266 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004267 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4269 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004270
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004272
Dominik Laskowski46470112019-08-02 13:13:11 -07004273 const auto it = dumpers.find(flag);
4274 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004276 } else if (!asProto) {
4277 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004278 }
4279
Mathias Agopian9795c422009-08-26 16:36:26 -07004280 if (locked) {
4281 mStateLock.unlock();
4282 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004283
Dominik Laskowski46470112019-08-02 13:13:11 -07004284 if (it == dumpers.end()) {
4285 const LayersProto layersProto = dumpProtoFromMainThread();
4286 if (asProto) {
4287 result.append(layersProto.SerializeAsString());
4288 } else {
4289 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4290 result.append(LayerProtoParser::layerTreeToString(layerTree));
4291 result.append("\n");
4292 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004293 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004294 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004296 return NO_ERROR;
4297}
4298
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004299status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4300 if (asProto && mTracing.isEnabled()) {
4301 mTracing.writeToFileAsync();
4302 }
4303
4304 return doDump(fd, DumpArgs(), asProto);
4305}
4306
Dominik Laskowskic2867142019-01-21 11:33:38 -08004307void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004308 mCurrentState.traverseInZOrder(
4309 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310}
4311
Dominik Laskowskic2867142019-01-21 11:33:38 -08004312void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004313 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004314
Dominik Laskowskic2867142019-01-21 11:33:38 -08004315 if (args.size() > 1) {
4316 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004317 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004318 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004319 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004320 }
Robert Carr2047fae2016-11-28 14:09:09 -08004321 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004322 } else {
4323 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324 }
4325}
4326
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004328 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004329 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004330 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331 }
Robert Carr2047fae2016-11-28 14:09:09 -08004332 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004333
Svetoslavd85084b2014-03-20 10:28:31 -07004334 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004335}
4336
Dominik Laskowskic2867142019-01-21 11:33:38 -08004337void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4338 mTimeStats->parseArgs(asProto, args, result);
4339}
4340
Jamie Gennis6547ff42013-07-16 20:12:42 -07004341// This should only be called from the main thread. Otherwise it would need
4342// the lock and should use mCurrentState rather than mDrawingState.
4343void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004344 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004345 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004346 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004347
4348 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4349}
4350
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004352 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004353
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004354 if (isLayerTripleBufferingDisabled())
4355 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004356
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4358 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4359 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4360 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4361 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4362 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004363 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004364}
4365
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004366void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004367 mScheduler->dump(result);
4368 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
4369
4370 mRefreshRateStats.dump(result);
4371 result.append("\n");
4372
Ana Krulec757f63a2019-01-25 10:46:18 -08004373 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004374 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004375 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004376 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004377
Ady Abraham42b3beb2019-07-09 18:09:52 -07004378 StringAppendF(&result, "Allowed Display Configs: ");
Dominik Laskowski98041832019-08-01 18:35:59 -07004379 for (const auto& [type, rate] : mRefreshRateConfigs.getRefreshRates()) {
4380 if (rate && isDisplayConfigAllowed(rate->configId)) {
4381 StringAppendF(&result, "%" PRIu32 " Hz, ", rate->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004382 }
4383 }
4384 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4385 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004386
Ana Krulecc2870422019-01-29 19:00:58 -08004387 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004388}
4389
Yiwei Zhang5434a782018-12-05 18:06:32 -08004390void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4391 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004392 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4393 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004394 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004395 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004396 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004397 }
David Sodman4a36e932017-11-07 14:29:47 -08004398 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004399 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004400 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004401 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4402 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004403}
4404
Dan Stozae77c7662016-05-13 11:37:28 -07004405void SurfaceFlinger::recordBufferingStats(const char* layerName,
4406 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004407 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4408 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004409 for (const auto& segment : history) {
4410 if (!segment.usedThirdBuffer) {
4411 stats.twoBufferTime += segment.totalTime;
4412 }
4413 if (segment.occupancyAverage < 1.0f) {
4414 stats.doubleBufferedTime += segment.totalTime;
4415 } else if (segment.occupancyAverage < 2.0f) {
4416 stats.tripleBufferedTime += segment.totalTime;
4417 }
4418 ++stats.numSegments;
4419 stats.totalTime += segment.totalTime;
4420 }
4421}
4422
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4424 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004425
4426 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4427 const size_t count = currentLayers.size();
4428 for (size_t i=0 ; i<count ; i++) {
4429 currentLayers[i]->dumpFrameEvents(result);
4430 }
4431}
4432
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004434 result.append("Buffering stats:\n");
4435 result.append(" [Layer name] <Active time> <Two buffer> "
4436 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004437 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004438 typedef std::tuple<std::string, float, float, float> BufferTuple;
4439 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004440 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004441 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004442 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004443 if (stats.numSegments == 0) {
4444 continue;
4445 }
4446 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4447 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4448 stats.totalTime;
4449 float doubleBufferRatio = static_cast<float>(
4450 stats.doubleBufferedTime) / stats.totalTime;
4451 float tripleBufferRatio = static_cast<float>(
4452 stats.tripleBufferedTime) / stats.totalTime;
4453 sorted.insert({activeTime, {name, twoBufferRatio,
4454 doubleBufferRatio, tripleBufferRatio}});
4455 }
4456 for (const auto& sortedPair : sorted) {
4457 float activeTime = sortedPair.first;
4458 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4460 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004461 }
4462 result.append("\n");
4463}
4464
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004466 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004467 const auto displayId = display->getId();
4468 if (!displayId) {
4469 continue;
4470 }
4471 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004472 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004473 continue;
4474 }
4475
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result,
4477 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4478 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004479 uint8_t port;
4480 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004481 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004482 result.append("no identification data\n");
4483 continue;
4484 }
4485
4486 if (!isEdid(data)) {
4487 result.append("unknown identification data: ");
4488 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004490 }
4491 result.append("\n");
4492 continue;
4493 }
4494
4495 const auto edid = parseEdid(data);
4496 if (!edid) {
4497 result.append("invalid EDID: ");
4498 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004500 }
4501 result.append("\n");
4502 continue;
4503 }
4504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004506 result.append(edid->displayName.data(), edid->displayName.length());
4507 result.append("\"\n");
4508 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004509}
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004512 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4514 StringAppendF(&result, "DisplayColorSetting: %s\n",
4515 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004516
4517 // TODO: print out if wide-color mode is active or not
4518
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004519 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004520 const auto displayId = display->getId();
4521 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004522 continue;
4523 }
4524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004526 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004527 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004529 }
4530
Lloyd Pique32cbe282018-10-19 13:09:22 -07004531 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, " Current color mode: %s (%d)\n",
4533 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004534 }
4535 result.append("\n");
4536}
4537
Vishnu Nair8406fd72019-07-30 11:29:31 -07004538LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004539 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004540 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004541 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004542 layer->writeToProtoDrawingState(layerProto, traceFlags);
4543 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004544 });
4545
4546 return layersProto;
4547}
4548
Vishnu Nair8406fd72019-07-30 11:29:31 -07004549LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4550 LayersProto layersProto;
4551 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4552 return layersProto;
4553}
4554
Dominik Laskowskic2867142019-01-21 11:33:38 -08004555void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4556 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 Colorizer colorizer(colorize);
4558
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559 // figure out if we're stuck somewhere
4560 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004562 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4563
4564 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004565 * Dump library configuration.
4566 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567
4568 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004569 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004570 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004571 appendSfConfigString(result);
4572 appendUiConfigString(result);
4573 appendGuiConfigString(result);
4574 result.append("\n");
4575
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 result.append("\nDisplay identification data:\n");
4577 dumpDisplayIdentificationData(result);
4578
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004579 result.append("\nWide-Color information:\n");
4580 dumpWideColorInfo(result);
4581
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004583 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004584 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004585 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004586 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004587
Andy McFadden41d67d72014-04-25 16:58:34 -07004588 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004589 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004590 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004591 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004592 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004593
Dan Stozab90cf072015-03-05 11:05:59 -08004594 dumpStaticScreenStats(result);
4595 result.append("\n");
4596
Alec Mouri40189b02019-03-05 15:07:54 -08004597 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4598 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4599 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004600
Dan Stozae77c7662016-05-13 11:37:28 -07004601 dumpBufferingStats(result);
4602
Andy McFadden4803b742012-09-24 19:07:20 -07004603 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 * Dump the visible layer list
4605 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004606 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004607 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4609 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004610 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004611
Chia-I Wu2f884132018-09-13 15:17:58 -07004612 {
Lloyd Pique207def92019-02-28 16:09:52 -08004613 StringAppendF(&result, "Composition layers\n");
4614 mDrawingState.traverseInZOrder([&](Layer* layer) {
4615 auto compositionLayer = layer->getCompositionLayer();
4616 if (compositionLayer) compositionLayer->dump(result);
4617 });
4618 }
4619
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004620 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004621 * Dump Display state
4622 */
4623
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004625 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004627 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004628 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004629 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004630 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004631
4632 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633 * Dump SurfaceFlinger global state
4634 */
4635
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004637 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004639
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004640 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004642 DebugEGLImageTracker::getInstance()->dump(result);
4643
Dominik Laskowski075d3172018-05-24 15:50:06 -07004644 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004645 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4646 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4648 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004649 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result,
4651 " transaction-flags : %08x\n"
4652 " gpu_to_cpu_unsupported : %d\n",
4653 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004654
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004655 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004656 displayId && getHwComposer().isConnected(*displayId)) {
4657 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result,
4659 " refresh-rate : %f fps\n"
4660 " x-dpi : %f\n"
4661 " y-dpi : %f\n",
4662 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4663 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004664 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667
Dan Stozae22aec72016-08-01 13:20:59 -07004668 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004669 * Tracing state
4670 */
4671 mTracing.dump(result);
4672 result.append("\n");
4673
4674 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004675 * HWC layer minidump
4676 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004677 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004678 const auto displayId = display->getId();
4679 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004680 continue;
4681 }
4682
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004684 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004685 const sp<DisplayDevice> displayDevice = display;
4686 mCurrentState.traverseInZOrder(
4687 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004688 result.append("\n");
4689 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690
4691 /*
4692 * Dump HWComposer state
4693 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004695 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004697 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004698 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004700
4701 /*
4702 * Dump gralloc state
4703 */
4704 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4705 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004706
4707 /*
4708 * Dump VrFlinger state if in use.
4709 */
4710 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4711 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004713 result.append("\n");
4714 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004715
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004716 result.append(mTimeStats->miniDump());
4717 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004718}
4719
Chia-I Wu28f320b2018-05-03 11:02:56 -07004720void SurfaceFlinger::updateColorMatrixLocked() {
4721 mat4 colorMatrix;
4722 if (mGlobalSaturationFactor != 1.0f) {
4723 // Rec.709 luma coefficients
4724 float3 luminance{0.213f, 0.715f, 0.072f};
4725 luminance *= 1.0f - mGlobalSaturationFactor;
4726 mat4 saturationMatrix = mat4(
4727 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4728 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4729 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4730 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4731 );
4732 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4733 } else {
4734 colorMatrix = mClientColorMatrix * mDaltonizer();
4735 }
4736
4737 if (mCurrentState.colorMatrix != colorMatrix) {
4738 mCurrentState.colorMatrix = colorMatrix;
4739 mCurrentState.colorMatrixChanged = true;
4740 setTransactionFlags(eTransactionNeeded);
4741 }
4742}
4743
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004744status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745#pragma clang diagnostic push
4746#pragma clang diagnostic error "-Wswitch-enum"
4747 switch (static_cast<ISurfaceComposerTag>(code)) {
4748 // These methods should at minimum make sure that the client requested
4749 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004750 case BOOT_FINISHED:
4751 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752 case CREATE_DISPLAY:
4753 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004754 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 case GET_ANIMATION_FRAME_STATS:
4756 case GET_HDR_CAPABILITIES:
4757 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004758 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004759 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004760 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004761 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004762 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004763 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004764 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004765 case GET_DISPLAYED_CONTENT_SAMPLE:
4766 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004767 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4768 IPCThreadState* ipc = IPCThreadState::self();
4769 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4770 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004771 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004772 }
Robert Carr1db73f62016-12-21 12:58:51 -08004773 return OK;
4774 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004776 IPCThreadState* ipc = IPCThreadState::self();
4777 const int pid = ipc->getCallingPid();
4778 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004779 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4780 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004781 return PERMISSION_DENIED;
4782 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004783 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004784 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785 // Used by apps to hook Choreographer to SurfaceFlinger.
4786 case CREATE_DISPLAY_EVENT_CONNECTION:
4787 // The following calls are currently used by clients that do not
4788 // request necessary permissions. However, they do not expose any secret
4789 // information, so it is OK to pass them.
4790 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004791 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004793 case GET_PHYSICAL_DISPLAY_IDS:
4794 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004796 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004797 case GET_DISPLAY_CONFIGS:
4798 case GET_DISPLAY_STATS:
4799 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4800 // Calling setTransactionState is safe, because you need to have been
4801 // granted a reference to Client* and Handle* to do anything with it.
4802 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004803 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004804 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004805 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004806 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004807 case IS_WIDE_COLOR_DISPLAY:
4808 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4809 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 return OK;
4811 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004812 case CAPTURE_LAYERS: {
4813 IPCThreadState* ipc = IPCThreadState::self();
4814 const int pid = ipc->getCallingPid();
4815 const int uid = ipc->getCallingUid();
4816 // allow media to capture layer for video thumbnails
4817 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4818 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4819 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4820 return PERMISSION_DENIED;
4821 }
4822 return OK;
4823 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004824 case CAPTURE_SCREEN:
4825 case ADD_REGION_SAMPLING_LISTENER:
4826 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004828 IPCThreadState* ipc = IPCThreadState::self();
4829 const int pid = ipc->getCallingPid();
4830 const int uid = ipc->getCallingUid();
4831 if ((uid != AID_GRAPHICS) &&
4832 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4833 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4834 return PERMISSION_DENIED;
4835 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836 return OK;
4837 }
4838 // The following codes are deprecated and should never be allowed to access SF.
4839 case CONNECT_DISPLAY_UNUSED:
4840 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4841 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4842 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004843 }
chaviw93df2ea2019-04-30 16:45:12 -07004844 case CAPTURE_SCREEN_BY_ID: {
4845 IPCThreadState* ipc = IPCThreadState::self();
4846 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004847 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004848 return OK;
4849 }
4850 return PERMISSION_DENIED;
4851 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004852 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853
4854 // These codes are used for the IBinder protocol to either interrogate the recipient
4855 // side of the transaction for its canonical interface descriptor or to dump its state.
4856 // We let them pass by default.
4857 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4858 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4859 code == IBinder::SYSPROPS_TRANSACTION) {
4860 return OK;
4861 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004862 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004864 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4866 return OK;
4867 }
4868 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4869 return PERMISSION_DENIED;
4870#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004871}
4872
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4874 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004875 status_t credentialCheck = CheckTransactCodeCredentials(code);
4876 if (credentialCheck != OK) {
4877 return credentialCheck;
4878 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4881 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004882 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004883 IPCThreadState* ipc = IPCThreadState::self();
4884 const int uid = ipc->getCallingUid();
4885 if (CC_UNLIKELY(uid != AID_SYSTEM
4886 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004887 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004888 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004889 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004890 return PERMISSION_DENIED;
4891 }
4892 int n;
4893 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004894 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004895 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004896 return NO_ERROR;
4897 case 1002: // SHOW_UPDATES
4898 n = data.readInt32();
4899 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004900 invalidateHwcGeometry();
4901 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004902 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004904 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004905 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004907 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004908 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004909 setTransactionFlags(
4910 eTransactionNeeded|
4911 eDisplayTransactionNeeded|
4912 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004913 return NO_ERROR;
4914 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004915 case 1006:{ // send empty update
4916 signalRefresh();
4917 return NO_ERROR;
4918 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004919 case 1008: // toggle use of hw composer
4920 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004921 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004922 invalidateHwcGeometry();
4923 repaintEverything();
4924 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004925 case 1009: // toggle use of transform hint
4926 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004927 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004928 invalidateHwcGeometry();
4929 repaintEverything();
4930 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004931 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004932 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004933 reply->writeInt32(0);
4934 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004935 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004936 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004937 return NO_ERROR;
4938 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004939 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004940 if (!display) {
4941 return NAME_NOT_FOUND;
4942 }
4943
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004944 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004945 return NO_ERROR;
4946 }
4947 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004948 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004949 // daltonize
4950 n = data.readInt32();
4951 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004952 case 1:
4953 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4954 break;
4955 case 2:
4956 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4957 break;
4958 case 3:
4959 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4960 break;
4961 default:
4962 mDaltonizer.setType(ColorBlindnessType::None);
4963 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004964 }
4965 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004966 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004967 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004968 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004969 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004970
4971 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004972 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004974 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004975 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004976 // apply a color matrix
4977 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004978 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004979 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004980 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004981 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004982 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004983 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004984 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004985 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004987 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004988
4989 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4990 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004991 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004992 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4993 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4994 }
4995
Chia-I Wu28f320b2018-05-03 11:02:56 -07004996 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004997 return NO_ERROR;
4998 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004999 case 1016: { // Unused.
5000 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005001 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005002 case 1017: {
5003 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005004 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005005 return NO_ERROR;
5006 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005007 case 1018: { // Modify Choreographer's phase offset
5008 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005009 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005010 return NO_ERROR;
5011 }
5012 case 1019: { // Modify SurfaceFlinger's phase offset
5013 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005014 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005015 return NO_ERROR;
5016 }
Irvel468051e2016-06-13 16:44:44 -07005017 case 1020: { // Layer updates interceptor
5018 n = data.readInt32();
5019 if (n) {
5020 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005021 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005022 }
5023 else{
5024 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005025 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005026 }
5027 return NO_ERROR;
5028 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005029 case 1021: { // Disable HWC virtual displays
5030 n = data.readInt32();
5031 mUseHwcVirtualDisplays = !n;
5032 return NO_ERROR;
5033 }
Romain Guy0147a172017-06-01 13:53:56 -07005034 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005035 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005036 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005037
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005039 return NO_ERROR;
5040 }
Romain Guy54f154a2017-10-24 21:40:32 +01005041 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005042 int32_t colorMode;
5043
Chia-I Wu0d711262018-05-21 15:19:35 -07005044 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005045 if (data.readInt32(&colorMode) == NO_ERROR) {
5046 mForceColorMode = static_cast<ColorMode>(colorMode);
5047 }
Romain Guy54f154a2017-10-24 21:40:32 +01005048 invalidateHwcGeometry();
5049 repaintEverything();
5050 return NO_ERROR;
5051 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005052 // Deprecate, use 1030 to check whether the device is color managed.
5053 case 1024: {
5054 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005055 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005056 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005057 n = data.readInt32();
5058 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005059 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005060 Mutex::Autolock lock(mStateLock);
5061 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005062 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005063 reply->writeInt32(NO_ERROR);
5064 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005065 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005066 bool writeFile = false;
5067 {
5068 Mutex::Autolock lock(mStateLock);
5069 mTracingEnabledChanged = true;
5070 writeFile = mTracing.disable();
5071 }
5072
5073 if (writeFile) {
5074 reply->writeInt32(mTracing.writeToFile());
5075 } else {
5076 reply->writeInt32(NO_ERROR);
5077 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005078 }
5079 return NO_ERROR;
5080 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005081 case 1026: { // Get layer tracing status
5082 reply->writeBool(mTracing.isEnabled());
5083 return NO_ERROR;
5084 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005085 // Is a DisplayColorSetting supported?
5086 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005087 const auto display = getDefaultDisplayDevice();
5088 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005089 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005090 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005091
5092 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5093 switch (setting) {
5094 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005095 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005096 break;
5097 case DisplayColorSetting::UNMANAGED:
5098 reply->writeBool(true);
5099 break;
5100 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005101 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005102 break;
5103 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005104 reply->writeBool(
5105 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005106 break;
5107 }
5108 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005109 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005110 // Is VrFlinger active?
5111 case 1028: {
5112 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005113 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005114 return NO_ERROR;
5115 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005116 // Set buffer size for SF tracing (value in KB)
5117 case 1029: {
5118 n = data.readInt32();
5119 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5120 ALOGW("Invalid buffer size: %d KB", n);
5121 reply->writeInt32(BAD_VALUE);
5122 return BAD_VALUE;
5123 }
5124
5125 ALOGD("Updating trace buffer to %d KB", n);
5126 mTracing.setBufferSize(n * 1024);
5127 reply->writeInt32(NO_ERROR);
5128 return NO_ERROR;
5129 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005130 // Is device color managed?
5131 case 1030: {
5132 reply->writeBool(useColorManagement);
5133 return NO_ERROR;
5134 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005135 // Override default composition data space
5136 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5137 // && adb shell stop zygote && adb shell start zygote
5138 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5139 // adb shell stop zygote && adb shell start zygote
5140 case 1031: {
5141 Mutex::Autolock _l(mStateLock);
5142 n = data.readInt32();
5143 if (n) {
5144 n = data.readInt32();
5145 if (n) {
5146 Dataspace dataspace = static_cast<Dataspace>(n);
5147 if (!validateCompositionDataspace(dataspace)) {
5148 return BAD_VALUE;
5149 }
5150 mDefaultCompositionDataspace = dataspace;
5151 }
5152 n = data.readInt32();
5153 if (n) {
5154 Dataspace dataspace = static_cast<Dataspace>(n);
5155 if (!validateCompositionDataspace(dataspace)) {
5156 return BAD_VALUE;
5157 }
5158 mWideColorGamutCompositionDataspace = dataspace;
5159 }
5160 } else {
5161 // restore composition data space.
5162 mDefaultCompositionDataspace = defaultCompositionDataspace;
5163 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5164 }
5165 return NO_ERROR;
5166 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005167 // Set trace flags
5168 case 1033: {
5169 n = data.readUint32();
5170 ALOGD("Updating trace flags to 0x%x", n);
5171 mTracing.setTraceFlags(n);
5172 reply->writeInt32(NO_ERROR);
5173 return NO_ERROR;
5174 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005175 case 1034: {
5176 // TODO(b/129297325): expose this via developer menu option
5177 n = data.readInt32();
5178 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005179 RefreshRateType type;
5180 {
5181 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5182 type = mDesiredActiveConfig.type;
5183 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005184 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005185 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005186 } else if (!n) {
5187 mRefreshRateOverlay.reset();
5188 }
5189 return NO_ERROR;
5190 }
Ady Abraham34392f72019-04-10 11:29:27 -07005191 case 1035: {
5192 n = data.readInt32();
5193 mDebugDisplayConfigSetByBackdoor = false;
5194 if (n >= 0) {
5195 const auto displayToken = getInternalDisplayToken();
5196 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5197 if (result != NO_ERROR) {
5198 return result;
5199 }
5200 mDebugDisplayConfigSetByBackdoor = true;
5201 }
5202 return NO_ERROR;
5203 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005204 }
5205 }
5206 return err;
5207}
5208
Steven Thomas6d8110b2017-08-31 18:24:21 -07005209void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005210 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005211 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005212}
5213
Ana Krulec7d1d6832018-12-27 11:10:09 -08005214void SurfaceFlinger::repaintEverythingForHWC() {
5215 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005216 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005217}
5218
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005219// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5220class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005221public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005222 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5223 ~WindowDisconnector() {
5224 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005225 }
5226
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005227private:
5228 ANativeWindow* mWindow;
5229 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005230};
5231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005232status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005233 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5234 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005235 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005236 uint32_t reqWidth, uint32_t reqHeight,
5237 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005238 ISurfaceComposer::Rotation rotation,
5239 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005242 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005243
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005244 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5245
Chia-I Wu20261cb2018-08-23 12:55:44 -07005246 sp<DisplayDevice> display;
5247 {
5248 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005249
Chia-I Wu20261cb2018-08-23 12:55:44 -07005250 display = getDisplayDeviceLocked(displayToken);
5251 if (!display) return BAD_VALUE;
5252
Chia-I Wucb023152018-08-28 12:57:23 -07005253 // set the requested width/height to the logical display viewport size
5254 // by default
5255 if (reqWidth == 0 || reqHeight == 0) {
5256 reqWidth = uint32_t(display->getViewport().width());
5257 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005258 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005259 }
5260
Peiyong Lin0e003c92018-09-17 11:09:51 -07005261 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005262 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005263
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005264 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5265 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005266 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005267 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005268}
5269
chaviw93df2ea2019-04-30 16:45:12 -07005270static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5271 switch (colorMode) {
5272 case ColorMode::DISPLAY_P3:
5273 case ColorMode::BT2100_PQ:
5274 case ColorMode::BT2100_HLG:
5275 case ColorMode::DISPLAY_BT2020:
5276 return Dataspace::DISPLAY_P3;
5277 default:
5278 return Dataspace::V0_SRGB;
5279 }
5280}
5281
5282const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5283 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5284 if (displayToken) {
5285 return getDisplayDeviceLocked(displayToken);
5286 }
5287 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5288 // may not have a displayId.
5289 for (const auto& [token, display] : mDisplays) {
5290 if (display->getLayerStack() == displayOrLayerStack) {
5291 return display;
5292 }
5293 }
5294 return nullptr;
5295}
5296
5297status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5298 sp<GraphicBuffer>* outBuffer) {
5299 sp<DisplayDevice> display;
5300 uint32_t width;
5301 uint32_t height;
5302 ui::Transform::orientation_flags captureOrientation;
5303 {
5304 Mutex::Autolock _l(mStateLock);
5305 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5306 if (!display) {
5307 return BAD_VALUE;
5308 }
5309
5310 width = uint32_t(display->getViewport().width());
5311 height = uint32_t(display->getViewport().height());
5312
5313 captureOrientation = fromSurfaceComposerRotation(
5314 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005315 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5316 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5317 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5318 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5319 }
chaviw93df2ea2019-04-30 16:45:12 -07005320 *outDataspace =
5321 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5322 }
5323
5324 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5325 false /* captureSecureLayers */);
5326
5327 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5328 std::placeholders::_1);
5329 bool ignored = false;
5330 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5331 false /* useIdentityTransform */,
5332 ignored /* outCapturedSecureLayers */);
5333}
5334
Robert Carr866455f2019-04-02 16:28:26 -07005335status_t SurfaceFlinger::captureLayers(
5336 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5337 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5338 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5339 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005340 ATRACE_CALL();
5341
5342 class LayerRenderArea : public RenderArea {
5343 public:
Robert Carr578038f2018-03-09 12:25:24 -08005344 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005345 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5346 bool childrenOnly)
5347 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005348 mLayer(layer),
5349 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005350 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005351 mFlinger(flinger),
5352 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005353 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005354 Rect getBounds() const override {
5355 const Layer::State& layerState(mLayer->getDrawingState());
5356 return mLayer->getBufferSize(layerState);
5357 }
Marissa Wall61c58622018-07-18 10:12:20 -07005358 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005359 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005360 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005361 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005362 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005363 }
chaviwa76b2712017-09-20 12:02:26 -07005364 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005365 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005366 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005367 Rect getSourceCrop() const override {
5368 if (mCrop.isEmpty()) {
5369 return getBounds();
5370 } else {
5371 return mCrop;
5372 }
5373 }
Robert Carr578038f2018-03-09 12:25:24 -08005374 class ReparentForDrawing {
5375 public:
5376 const sp<Layer>& oldParent;
5377 const sp<Layer>& newParent;
5378
Vishnu Nair4351ad52019-02-11 14:13:02 -08005379 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5380 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005381 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005382 // Compute and cache the bounds for the new parent layer.
5383 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005384 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005385 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005386 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005387 };
5388
5389 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005390 const Rect sourceCrop = getSourceCrop();
5391 // no need to check rotation because there is none
5392 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5393 sourceCrop.height() != getReqHeight();
5394
Robert Carr578038f2018-03-09 12:25:24 -08005395 if (!mChildrenOnly) {
5396 mTransform = mLayer->getTransform().inverse();
5397 drawLayers();
5398 } else {
5399 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005400 // In the "childrenOnly" case we reparent the children to a screenshot
5401 // layer which has no properties set and which does not draw.
5402 sp<ContainerLayer> screenshotParentLayer =
5403 mFlinger->getFactory().createContainerLayer(
5404 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5405 bounds.getWidth(), bounds.getHeight(), 0,
5406 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005407
Vishnu Nair4351ad52019-02-11 14:13:02 -08005408 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005409 drawLayers();
5410 }
5411 }
chaviwa76b2712017-09-20 12:02:26 -07005412
chaviwa76b2712017-09-20 12:02:26 -07005413 private:
chaviw7206d492017-11-10 16:16:12 -08005414 const sp<Layer> mLayer;
5415 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005416
Peiyong Linefefaac2018-08-17 12:27:51 -07005417 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005418 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005419
5420 SurfaceFlinger* mFlinger;
5421 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005422 };
5423
Robert Carrc0df3122019-04-11 13:18:21 -07005424 int reqWidth = 0;
5425 int reqHeight = 0;
5426 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005427 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005428 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005429
Robert Carrc0df3122019-04-11 13:18:21 -07005430 {
5431 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005432
Robert Carrc0df3122019-04-11 13:18:21 -07005433 parent = fromHandle(layerHandleBinder);
5434 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5435 ALOGE("captureLayers called with an invalid or removed parent");
5436 return NAME_NOT_FOUND;
5437 }
5438
5439 const int uid = IPCThreadState::self()->getCallingUid();
5440 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5441 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5442 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5443 return PERMISSION_DENIED;
5444 }
5445
5446 if (sourceCrop.width() <= 0) {
5447 crop.left = 0;
5448 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5449 }
5450
5451 if (sourceCrop.height() <= 0) {
5452 crop.top = 0;
5453 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5454 }
5455 reqWidth = crop.width() * frameScale;
5456 reqHeight = crop.height() * frameScale;
5457
5458 for (const auto& handle : excludeHandles) {
5459 sp<Layer> excludeLayer = fromHandle(handle);
5460 if (excludeLayer != nullptr) {
5461 excludeLayers.emplace(excludeLayer);
5462 } else {
5463 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5464 return NAME_NOT_FOUND;
5465 }
5466 }
5467 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005468
Chia-I Wu20261cb2018-08-23 12:55:44 -07005469 // really small crop or frameScale
5470 if (reqWidth <= 0) {
5471 reqWidth = 1;
5472 }
5473 if (reqHeight <= 0) {
5474 reqHeight = 1;
5475 }
5476
Robert Carr866455f2019-04-02 16:28:26 -07005477 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5478 auto traverseLayers = [parent, childrenOnly,
5479 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005480 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5481 if (!layer->isVisible()) {
5482 return;
Robert Carr578038f2018-03-09 12:25:24 -08005483 } else if (childrenOnly && layer == parent.get()) {
5484 return;
chaviwa76b2712017-09-20 12:02:26 -07005485 }
Robert Carr866455f2019-04-02 16:28:26 -07005486
5487 sp<Layer> p = layer;
5488 while (p != nullptr) {
5489 if (excludeLayers.count(p) != 0) {
5490 return;
5491 }
5492 p = p->getParent();
5493 }
5494
chaviwa76b2712017-09-20 12:02:26 -07005495 visitor(layer);
5496 });
5497 };
Robert Carr108b2c72019-04-02 16:32:58 -07005498
5499 bool outCapturedSecureLayers = false;
5500 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5501 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005502}
5503
5504status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5505 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005506 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005507 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005508 bool useIdentityTransform,
5509 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005510 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005511
Peiyong Lin0e003c92018-09-17 11:09:51 -07005512 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005513 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5514 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005515 *outBuffer =
5516 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5517 static_cast<android_pixel_format>(reqPixelFormat), 1,
5518 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519
Robert Carr108b2c72019-04-02 16:32:58 -07005520 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5521 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005522}
5523
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005524status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5525 TraverseLayersFunction traverseLayers,
5526 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005527 bool useIdentityTransform,
5528 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005529 // This mutex protects syncFd and captureResult for communication of the return values from the
5530 // main thread back to this Binder thread
5531 std::mutex captureMutex;
5532 std::condition_variable captureCondition;
5533 std::unique_lock<std::mutex> captureLock(captureMutex);
5534 int syncFd = -1;
5535 std::optional<status_t> captureResult;
5536
Robert Carr03480e22018-01-04 16:02:06 -08005537 const int uid = IPCThreadState::self()->getCallingUid();
5538 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5539
Dominik Laskowski8c001672018-05-30 16:52:06 -07005540 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005541 // If there is a refresh pending, bug out early and tell the binder thread to try again
5542 // after the refresh.
5543 if (mRefreshPending) {
5544 ATRACE_NAME("Skipping screenshot for now");
5545 std::unique_lock<std::mutex> captureLock(captureMutex);
5546 captureResult = std::make_optional<status_t>(EAGAIN);
5547 captureCondition.notify_one();
5548 return;
5549 }
5550
5551 status_t result = NO_ERROR;
5552 int fd = -1;
5553 {
5554 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005555 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005556 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005557 useIdentityTransform, forSystem, &fd,
5558 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005559 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005560 }
5561
5562 {
5563 std::unique_lock<std::mutex> captureLock(captureMutex);
5564 syncFd = fd;
5565 captureResult = std::make_optional<status_t>(result);
5566 captureCondition.notify_one();
5567 }
5568 });
5569
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005570 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005571 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005572 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005573 while (*captureResult == EAGAIN) {
5574 captureResult.reset();
5575 result = postMessageAsync(message);
5576 if (result != NO_ERROR) {
5577 return result;
5578 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 }
5581 result = *captureResult;
5582 }
5583
5584 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005585 sync_wait(syncFd, -1);
5586 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005587 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005588
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005589 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005590}
5591
chaviwa76b2712017-09-20 12:02:26 -07005592void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005593 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005594 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5595 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005596 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005597
chaviwa76b2712017-09-20 12:02:26 -07005598 const auto reqWidth = renderArea.getReqWidth();
5599 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005600 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005601 const auto transform = renderArea.getTransform();
5602 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005603
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005604 renderengine::DisplaySettings clientCompositionDisplay;
5605 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005606
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005607 // assume that bounds are never offset, and that they are the same as the
5608 // buffer bounds.
5609 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005610 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005611 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005612
5613 // Now take into account the rotation flag. We append a transform that
5614 // rotates the layer stack about the origin, then translate by buffer
5615 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005616 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005617 int displacementX = 0;
5618 int displacementY = 0;
5619 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5620 switch (rotation) {
5621 case ui::Transform::ROT_90:
5622 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005623 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005624 break;
5625 case ui::Transform::ROT_180:
5626 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005627 displacementY = renderArea.getBounds().getWidth();
5628 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005629 break;
5630 case ui::Transform::ROT_270:
5631 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005632 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 break;
5634 default:
5635 break;
5636 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005637
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005638 // We need to transform the clipping window into the right spot.
5639 // First, rotate the clipping rectangle by the rotation hint to get the
5640 // right orientation
5641 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5642 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5643 const vec4 rotClipTL = rotMatrix * clipTL;
5644 const vec4 rotClipBR = rotMatrix * clipBR;
5645 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5646 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5647 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5648 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5649
5650 // Now reposition the clipping rectangle with the displacement vector
5651 // computed above.
5652 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005653 clientCompositionDisplay.clip =
5654 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5655 newClipRight + displacementX, newClipBottom + displacementY);
5656
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005658 clientCompositionDisplay.globalTransform =
5659 clipTransform * clientCompositionDisplay.globalTransform;
5660
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5662 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005663
chaviw50da5042018-04-09 13:49:37 -07005664 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005665
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 renderengine::LayerSettings fillLayer;
5667 fillLayer.source.buffer.buffer = nullptr;
5668 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5669 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5670 fillLayer.alpha = half(alpha);
5671 clientCompositionLayers.push_back(fillLayer);
5672
5673 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005674 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005675 const bool supportProtectedContent = false;
5676 Region clip(renderArea.getBounds());
5677 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5678 clip,
5679 useIdentityTransform,
5680 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5681 renderArea.isSecure(),
5682 supportProtectedContent,
5683 clearRegion,
5684 };
5685 auto result = layer->prepareClientComposition(targetSettings);
5686 if (result) {
5687 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005688 }
chaviwa76b2712017-09-20 12:02:26 -07005689 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005690
5691 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005692 // Use an empty fence for the buffer fence, since we just created the buffer so
5693 // there is no need for synchronization with the GPU.
5694 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005696 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005697 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005698 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699
5700 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005701}
5702
chaviwa76b2712017-09-20 12:02:26 -07005703status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5704 TraverseLayersFunction traverseLayers,
5705 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005706 bool useIdentityTransform, bool forSystem,
5707 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005708 ATRACE_CALL();
5709
chaviwa76b2712017-09-20 12:02:26 -07005710 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005711 outCapturedSecureLayers =
5712 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005713 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005714
Robert Carr03480e22018-01-04 16:02:06 -08005715 // We allow the system server to take screenshots of secure layers for
5716 // use in situations like the Screen-rotation animation and place
5717 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005718 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005719 ALOGW("FB is protected: PERMISSION_DENIED");
5720 return PERMISSION_DENIED;
5721 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005723 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005724}
5725
chaviw95ef3c42019-02-14 10:55:09 -08005726void SurfaceFlinger::setInputWindowsFinished() {
5727 Mutex::Autolock _l(mStateLock);
5728
5729 mPendingSyncInputWindows = false;
5730 mTransactionCV.broadcast();
5731}
chaviw5f21a5e2019-02-14 10:00:34 -08005732
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005733// ---------------------------------------------------------------------------
5734
Dan Stoza412903f2017-04-27 13:42:17 -07005735void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5736 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005737}
5738
Dan Stoza412903f2017-04-27 13:42:17 -07005739void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5740 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005741}
5742
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005743void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005744 const LayerVector::Visitor& visitor) {
5745 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005746 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005747 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005748 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005749 continue;
5750 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005751 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005752 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005753 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005754 return;
5755 }
chaviwa76b2712017-09-20 12:02:26 -07005756 if (!layer->isVisible()) {
5757 return;
5758 }
5759 visitor(layer);
5760 });
5761 }
5762}
5763
Dominik Laskowski22488f62019-03-28 09:53:04 -07005764void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5765 const std::vector<int32_t>& allowedConfigs) {
5766 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005767 return;
5768 }
5769
5770 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005771 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08005772
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005773 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07005774 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005775 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005776 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005777 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005778 setDesiredActiveConfig(
5779 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005780 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005781 }
5782 }
Ady Abraham838de062019-02-04 10:24:03 -08005783}
5784
Dominik Laskowski22488f62019-03-28 09:53:04 -07005785status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005786 const std::vector<int32_t>& allowedConfigs) {
5787 ATRACE_CALL();
5788
Dominik Laskowski22488f62019-03-28 09:53:04 -07005789 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005790 return BAD_VALUE;
5791 }
5792
Ady Abraham34392f72019-04-10 11:29:27 -07005793 if (mDebugDisplayConfigSetByBackdoor) {
5794 // ignore this request as config is overridden by backdoor
5795 return NO_ERROR;
5796 }
5797
Ady Abraham838de062019-02-04 10:24:03 -08005798 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005799 const auto display = getDisplayDeviceLocked(displayToken);
5800 if (!display) {
5801 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5802 displayToken.get());
5803 } else if (display->isVirtual()) {
5804 ALOGW("Attempt to set allowed display configs for virtual display");
5805 } else {
5806 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5807 }
Ady Abraham838de062019-02-04 10:24:03 -08005808 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005809
Ady Abraham838de062019-02-04 10:24:03 -08005810 return NO_ERROR;
5811}
5812
Dominik Laskowski22488f62019-03-28 09:53:04 -07005813status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005814 std::vector<int32_t>* outAllowedConfigs) {
5815 ATRACE_CALL();
5816
Dominik Laskowski22488f62019-03-28 09:53:04 -07005817 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005818 return BAD_VALUE;
5819 }
5820
Dominik Laskowski22488f62019-03-28 09:53:04 -07005821 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005822
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005823 const auto display = getDisplayDeviceLocked(displayToken);
5824 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005825 return NAME_NOT_FOUND;
5826 }
5827
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005828 if (display->isPrimary()) {
5829 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5830 }
5831
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005832 return NO_ERROR;
5833}
5834
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005835void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005836 mFlinger->setInputWindowsFinished();
5837}
5838
Robert Carrc0df3122019-04-11 13:18:21 -07005839sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5840 BBinder *b = handle->localBinder();
5841 if (b == nullptr) {
5842 return nullptr;
5843 }
5844 auto it = mLayersByLocalBinderToken.find(b);
5845 if (it != mLayersByLocalBinderToken.end()) {
5846 return it->second.promote();
5847 }
5848 return nullptr;
5849}
5850
Alec Mouri4545a8a2019-08-08 20:05:32 -07005851void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5852 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5853}
5854
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005855} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005856
Mathias Agopian3f844832013-08-07 21:24:32 -07005857#if defined(__gl_h_)
5858#error "don't include gl/gl.h in this file"
5859#endif
5860
5861#if defined(__gl2_h_)
5862#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005863#endif