blob: e8902b3c623470410f647166ef6175d2e0518d0d [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"
Mikael Pessa90092f42019-08-26 17:22:04 -0700101#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700102#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700104#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105#include "Scheduler/EventControlThread.h"
106#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700107#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700108#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700109#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700110#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800111#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112
Mathias Agopianff2ed702013-09-01 21:36:12 -0700113#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700114
David Sodman7e4ae112018-02-09 15:02:28 -0800115#include "android-base/stringprintf.h"
116
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800118#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
119#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700120#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900121#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122
chaviw1d044282017-09-27 12:19:28 -0700123#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700127
Jaesoo Lee43518572017-01-23 19:03:16 +0900128using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900129using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900130using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131
Ady Abraham8532d012019-05-08 14:50:56 -0700132using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700134using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700135using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800136using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700137using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700138using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900139
Steven Thomasb02664d2017-07-26 18:48:28 -0700140namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700141
142#pragma clang diagnostic push
143#pragma clang diagnostic error "-Wswitch-enum"
144
145bool isWideColorMode(const ColorMode colorMode) {
146 switch (colorMode) {
147 case ColorMode::DISPLAY_P3:
148 case ColorMode::ADOBE_RGB:
149 case ColorMode::DCI_P3:
150 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700151 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700152 case ColorMode::BT2100_PQ:
153 case ColorMode::BT2100_HLG:
154 return true;
155 case ColorMode::NATIVE:
156 case ColorMode::STANDARD_BT601_625:
157 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
158 case ColorMode::STANDARD_BT601_525:
159 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
160 case ColorMode::STANDARD_BT709:
161 case ColorMode::SRGB:
162 return false;
163 }
164 return false;
165}
166
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700167ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
168 switch (rotation) {
169 case ISurfaceComposer::eRotateNone:
170 return ui::Transform::ROT_0;
171 case ISurfaceComposer::eRotate90:
172 return ui::Transform::ROT_90;
173 case ISurfaceComposer::eRotate180:
174 return ui::Transform::ROT_180;
175 case ISurfaceComposer::eRotate270:
176 return ui::Transform::ROT_270;
177 }
178 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
179 return ui::Transform::ROT_0;
180}
181
Peiyong Linfca547f2018-07-09 13:03:33 -0700182#pragma clang diagnostic pop
183
Steven Thomasb02664d2017-07-26 18:48:28 -0700184class ConditionalLock {
185public:
186 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
187 if (lock) {
188 mMutex.lock();
189 }
190 }
191 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
192private:
193 Mutex& mMutex;
194 bool mLocked;
195};
Peiyong Linfca547f2018-07-09 13:03:33 -0700196
Peiyong Lin9d846a52018-11-05 13:18:20 -0800197// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
198bool validateCompositionDataspace(Dataspace dataspace) {
199 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
200}
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202} // namespace anonymous
203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204// ---------------------------------------------------------------------------
205
Mathias Agopian99b49842011-06-27 16:05:52 -0700206const String16 sHardwareTest("android.permission.HARDWARE_TEST");
207const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
208const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
209const String16 sDump("android.permission.DUMP");
210
211// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800214uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800215bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800216bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800217int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600218bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700219int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700220bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700221bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700222Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
223ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
224Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700226
Kalle Raitaa099a242017-01-11 11:17:29 -0800227std::string getHwcServiceName() {
228 char value[PROPERTY_VALUE_MAX] = {};
229 property_get("debug.sf.hwc_service_name", value, "default");
230 ALOGI("Using HWComposer service: '%s'", value);
231 return std::string(value);
232}
233
234bool useTrebleTestingOverride() {
235 char value[PROPERTY_VALUE_MAX] = {};
236 property_get("debug.sf.treble_testing_override", value, "false");
237 ALOGI("Treble testing override: '%s'", value);
238 return std::string(value) == "true";
239}
240
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
242 switch(displayColorSetting) {
243 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700244 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700246 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800247 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Enhanced");
249 default:
250 return std::string("Unknown ") +
251 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800253}
254
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700255SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800256
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700257SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
258 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259 mInterceptor(mFactory.createSurfaceInterceptor(this)),
260 mTimeStats(mFactory.createTimeStats()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700261 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700263 mCompositionEngine(mFactory.createCompositionEngine()),
264 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800265
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 mDefaultCompositionDataspace =
287 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700288 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
289 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 defaultCompositionDataspace = mDefaultCompositionDataspace;
291 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
292 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
293 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
294 wideColorGamutCompositionPixelFormat =
295 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700296
Yichi Chenda901bf2019-06-28 14:58:27 +0800297 mColorSpaceAgnosticDataspace =
298 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
303 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
304 switch (tmpPrimaryDisplayOrientation) {
305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 property_get("debug.sf.showupdates", value, "0");
329 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700331 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000332
333 // DDMS debugging deprecated (b/120782499)
334 property_get("debug.sf.ddms", value, "0");
335 int debugDdms = atoi(value);
336 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700337
338 property_get("debug.sf.disable_backpressure", value, "0");
339 mPropagateBackpressure = !atoi(value);
340 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700341
Ady Abraham4658e112019-07-22 13:07:26 -0700342 property_get("debug.sf.enable_gl_backpressure", value, "0");
343 mPropagateBackpressureClientComposition = atoi(value);
344 ALOGI_IF(mPropagateBackpressureClientComposition,
345 "Enabling backpressure propagation for Client Composition");
346
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800347 property_get("debug.sf.enable_hwc_vds", value, "0");
348 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800349 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800351 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800352 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700354
Yiwei Zhang243b3782018-05-15 17:40:04 -0700355 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700356 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
357 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
358
Ana Krulece5a06e02019-03-06 17:09:03 -0800359 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800360 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800361
362 int int_value = atoi(value);
363 if (int_value) {
364 mUseSmart90ForVideo = true;
365 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800366
Dan Stozaec460082018-12-17 15:35:09 -0800367 property_get("debug.sf.luma_sampling", value, "1");
368 mLumaSampling = atoi(value);
369
Romain Guy11d63f42017-07-20 12:47:14 -0700370 // We should be reading 'persist.sys.sf.color_saturation' here
371 // but since /data may be encrypted, we need to wait until after vold
372 // comes online to attempt to read the property. The property is
373 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800374
375 if (useTrebleTestingOverride()) {
376 // Without the override SurfaceFlinger cannot connect to HIDL
377 // services that are not listed in the manifests. Considered
378 // deriving the setting from the set service name, but it
379 // would be brittle if the name that's not 'default' is used
380 // for production purposes later on.
381 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385void SurfaceFlinger::onFirstRef()
386{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800387 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800388}
389
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700390SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391
Dan Stozac7014012014-02-14 15:03:43 -0800392void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393{
394 // the window manager died on us. prepare its eulogy.
395
Andy McFadden13a082e2012-08-24 10:16:42 -0700396 // restore initial conditions (default device unblank, etc)
397 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398
399 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700400 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800401}
402
Robert Carr1db73f62016-12-21 12:58:51 -0800403static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700404 status_t err = client->initCheck();
405 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407 }
Robert Carr1db73f62016-12-21 12:58:51 -0800408 return nullptr;
409}
410
411sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
412 return initClient(new Client(this));
413}
414
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700415sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
416 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417{
418 class DisplayToken : public BBinder {
419 sp<SurfaceFlinger> flinger;
420 virtual ~DisplayToken() {
421 // no more references, this display must be terminated
422 Mutex::Autolock _l(flinger->mStateLock);
423 flinger->mCurrentState.displays.removeItem(this);
424 flinger->setTransactionFlags(eDisplayTransactionNeeded);
425 }
426 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700427 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700428 : flinger(flinger) {
429 }
430 };
431
432 sp<BBinder> token = new DisplayToken(this);
433
434 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700435 // Display ID is assigned when virtual display is allocated by HWC.
436 DisplayDeviceState state;
437 state.isSecure = secure;
438 state.displayName = displayName;
439 mCurrentState.displays.add(token, state);
440 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 return token;
442}
443
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700444void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 Mutex::Autolock _l(mStateLock);
446
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
448 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700449 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700450 return;
451 }
452
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
454 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 ALOGE("destroyDisplay called for non-virtual display");
456 return;
457 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 mInterceptor->saveDisplayDeletion(state.sequenceId);
459 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 setTransactionFlags(eDisplayTransactionNeeded);
461}
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
464 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800466 const auto internalDisplayId = getInternalDisplayIdLocked();
467 if (!internalDisplayId) {
468 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 }
470
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800471 std::vector<PhysicalDisplayId> displayIds;
472 displayIds.reserve(mPhysicalDisplayTokens.size());
473 displayIds.push_back(internalDisplayId->value);
474
475 for (const auto& [id, token] : mPhysicalDisplayTokens) {
476 if (id != *internalDisplayId) {
477 displayIds.push_back(id.value);
478 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 return displayIds;
482}
483
484sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
485 Mutex::Autolock lock(mStateLock);
486 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487}
488
Ady Abraham37965d42018-11-01 13:43:32 -0700489status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
490 if (!outGetColorManagement) {
491 return BAD_VALUE;
492 }
493 *outGetColorManagement = useColorManagement;
494 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700495}
496
Lloyd Pique441d5042018-10-18 16:49:51 -0700497HWComposer& SurfaceFlinger::getHwComposer() const {
498 return mCompositionEngine->getHwComposer();
499}
500
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700501renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
502 return mCompositionEngine->getRenderEngine();
503}
504
Lloyd Pique70d91362018-10-18 16:02:55 -0700505compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
506 return *mCompositionEngine.get();
507}
508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509void SurfaceFlinger::bootFinished()
510{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700511 if (mStartPropertySetThread->join() != NO_ERROR) {
512 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514 const nsecs_t now = systemTime();
515 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000516 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517
Mikael Pessa90092f42019-08-26 17:22:04 -0700518 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700519
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520 // wait patiently for the window manager death
521 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700522 mWindowManager = defaultServiceManager()->getService(name);
523 if (mWindowManager != 0) {
524 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525 }
Robert Carr720e5062018-07-30 17:45:14 -0700526 sp<IBinder> input(defaultServiceManager()->getService(
527 String16("inputflinger")));
528 if (input == nullptr) {
529 ALOGE("Failed to link to input service");
530 } else {
531 mInputFlinger = interface_cast<IInputFlinger>(input);
532 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
Steven Thomas050b2c82017-03-06 11:45:16 -0800534 if (mVrFlinger) {
535 mVrFlinger->OnBootFinished();
536 }
537
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700539 // formerly we would just kill the process, but we now ask it to exit so it
540 // can choose where to stop the animation.
541 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700542
543 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
544 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
545 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700546
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800548 readPersistentProperties();
549 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800550
Ady Abraham97d04232019-03-05 19:48:12 -0800551 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700552 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700553 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800554
Dominik Laskowski22488f62019-03-28 09:53:04 -0700555 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800556 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800557 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800558 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800559 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800560 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800561}
562
Dan Stoza436ccf32018-06-21 12:10:12 -0700563uint32_t SurfaceFlinger::getNewTexture() {
564 {
565 std::lock_guard lock(mTexturePoolMutex);
566 if (!mTexturePool.empty()) {
567 uint32_t name = mTexturePool.back();
568 mTexturePool.pop_back();
569 ATRACE_INT("TexturePoolSize", mTexturePool.size());
570 return name;
571 }
572
573 // The pool was too small, so increase it for the future
574 ++mTexturePoolSize;
575 }
576
577 // The pool was empty, so we need to get a new texture name directly using a
578 // blocking call to the main thread
579 uint32_t name = 0;
580 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
581 return name;
582}
583
Mathias Agopian3f844832013-08-07 21:24:32 -0700584void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700585 std::lock_guard lock(mTexturePoolMutex);
586 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
587 // to actually delete this or not based on mTexturePoolSize
588 mTexturePool.push_back(texture);
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700590}
591
Wei Wangf9b05ee2017-07-19 20:59:39 -0700592// Do not call property_set on main thread which will be blocked by init
593// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700595 ALOGI( "SurfaceFlinger's main thread ready to run. "
596 "Initializing graphics H/W...");
597
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700598 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800602 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700603 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
604 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800605 auto resyncCallback =
606 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800607
Ana Krulecc2870422019-01-29 19:00:58 -0800608 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700609 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700610 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800611 resyncCallback,
612 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700613 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700614 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700615 mPhaseOffsets->getOffsetThresholdForNextVsync(),
616 resyncCallback, [this](nsecs_t timestamp) {
617 mInterceptor->saveVSyncEvent(timestamp);
618 });
Ana Krulecc2870422019-01-29 19:00:58 -0800619
620 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700621
622 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
623 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800624
Kevin DuBois413287f2019-02-25 08:46:47 -0800625 mRegionSamplingThread =
626 new RegionSamplingThread(*this, *mScheduler,
627 RegionSamplingThread::EnvironmentTimingTunables());
628
Steven Thomasb02664d2017-07-26 18:48:28 -0700629 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700630 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700631 renderEngineFeature |= (useColorManagement ?
632 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700633 renderEngineFeature |= (useContextPriority ?
634 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700635 renderEngineFeature |=
636 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
637 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700638
639 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800640 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700641 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700642 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800643 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700644
645 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
646 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700647 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
648 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800649 // Process any initial hotplug and resulting display changes.
650 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 const auto display = getDefaultDisplayDeviceLocked();
652 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700653 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700672 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Mathias Agopian92a979a2012-08-02 18:32:23 -0700680 // initialize our drawing state
681 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700682
Andy McFadden13a082e2012-08-24 10:16:42 -0700683 // set initial conditions (e.g. unblank default device)
684 initializeDisplays();
685
Steven Thomas137d4bc2019-07-25 16:55:14 -0700686 char primeShaderCache[PROPERTY_VALUE_MAX];
687 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
688 if (atoi(primeShaderCache)) {
689 getRenderEngine().primeCache();
690 }
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693
694 const bool presentFenceReliable =
695 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
696 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697
698 if (mStartPropertySetThread->Start() != NO_ERROR) {
699 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Alec Mouri93bc83d2019-04-17 14:47:43 -0700702 mScheduler->setChangeRefreshRateCallback(
703 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
704 Mutex::Autolock lock(mStateLock);
705 setRefreshRateTo(type, event);
706 });
Alec Mouri7f015182019-07-11 13:56:22 -0700707 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
708 Mutex::Autolock lock(mStateLock);
709 const auto display = getDefaultDisplayDeviceLocked();
710 if (!display) {
711 // If we don't have a default display the fallback to the default
712 // refresh rate type
713 return RefreshRateType::DEFAULT;
714 }
715
716 const int configId = display->getActiveConfig();
717 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
718 if (refresh && refresh->configId == configId) {
719 return type;
720 }
721 }
722 // This should never happen, but just gracefully fallback to default.
723 return RefreshRateType::DEFAULT;
724 });
Alec Mouridc28b372019-04-18 21:17:13 -0700725 mScheduler->setGetVsyncPeriodCallback([this] {
726 Mutex::Autolock lock(mStateLock);
727 return getVsyncPeriod();
728 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700729
Dominik Laskowski22488f62019-03-28 09:53:04 -0700730 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
731 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800732
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700734}
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 Mutex::Autolock _l(mStateLock);
738
Romain Guy11d63f42017-07-20 12:47:14 -0700739 char value[PROPERTY_VALUE_MAX];
740
741 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700743 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100745
746 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700747 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800748
749 property_get("persist.sys.sf.color_mode", value, "0");
750 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700751}
752
Mathias Agopiana67e4182012-06-19 17:26:12 -0700753void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800754 // Start boot animation service by setting a property mailbox
755 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800757 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 if (mStartPropertySetThread->join() != NO_ERROR) {
759 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800760 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700764 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
Mathias Agopian875d8e12013-06-07 15:35:48 -0700767size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700768 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700769}
770
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800771// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800772
Jamie Gennis582270d2011-08-17 18:19:00 -0700773bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800774 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800775 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800776 return authenticateSurfaceTextureLocked(bufferProducer);
777}
778
779bool SurfaceFlinger::authenticateSurfaceTextureLocked(
780 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800781 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800782 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800783}
784
Brian Anderson6b376712017-04-04 10:51:39 -0700785status_t SurfaceFlinger::getSupportedFrameTimestamps(
786 std::vector<FrameEvent>* outSupported) const {
787 *outSupported = {
788 FrameEvent::REQUESTED_PRESENT,
789 FrameEvent::ACQUIRE,
790 FrameEvent::LATCH,
791 FrameEvent::FIRST_REFRESH_START,
792 FrameEvent::LAST_REFRESH_START,
793 FrameEvent::GPU_COMPOSITION_DONE,
794 FrameEvent::DEQUEUE_READY,
795 FrameEvent::RELEASE,
796 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700797 ConditionalLock _l(mStateLock,
798 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700799 if (!getHwComposer().hasCapability(
800 HWC2::Capability::PresentFenceIsNotReliable)) {
801 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
802 }
803 return NO_ERROR;
804}
805
Dominik Laskowski22488f62019-03-28 09:53:04 -0700806status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
807 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 return BAD_VALUE;
810 }
811
Dominik Laskowski22488f62019-03-28 09:53:04 -0700812 Mutex::Autolock lock(mStateLock);
813
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800814 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700815 if (!displayId) {
816 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 // TODO: Not sure if display density should handled by SF any longer
820 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700823 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800824 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 }
827 return density;
828 }
829 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("ro.sf.lcd_density"); }
834 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dominik Laskowski075d3172018-05-24 15:50:06 -0700838 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 DisplayInfo info = DisplayInfo();
840
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 float xdpi = hwConfig->getDpiX();
842 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700844 info.w = hwConfig->getWidth();
845 info.h = hwConfig->getHeight();
846 // Default display viewport to display width and height
847 info.viewportW = info.w;
848 info.viewportH = info.h;
849
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800850 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 // The density of the device is provided by a build property
852 float density = Density::getBuildDensity() / 160.0f;
853 if (density == 0) {
854 // the build doesn't provide a density -- this is wrong!
855 // use xdpi instead
856 ALOGE("ro.sf.lcd_density must be defined as a build property");
857 density = xdpi / 160.0f;
858 }
859 if (Density::getEmuDensity()) {
860 // if "qemu.sf.lcd_density" is specified, it overrides everything
861 xdpi = ydpi = density = Density::getEmuDensity();
862 density /= 160.0f;
863 }
864 info.density = density;
865
866 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700867 const auto display = getDefaultDisplayDeviceLocked();
868 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700869
870 // This is for screenrecord
871 const Rect viewport = display->getViewport();
872 if (viewport.isValid()) {
873 info.viewportW = uint32_t(viewport.getWidth());
874 info.viewportH = uint32_t(viewport.getHeight());
875 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 } else {
877 // TODO: where should this value come from?
878 static const int TV_DENSITY = 213;
879 info.density = TV_DENSITY / 160.0f;
880 info.orientation = 0;
881 }
882
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 info.xdpi = xdpi;
884 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700886 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
887 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
888 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700902 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800907 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulecc2870422019-01-29 19:00:58 -0800923 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return NO_ERROR;
925}
926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
928 const auto display = getDisplayDevice(displayToken);
929 if (!display) {
930 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800931 return BAD_VALUE;
932 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700935}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700936
Ady Abraham03b02dd2019-03-21 15:40:11 -0700937void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800939
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800941 // config twice. However event generation config might have changed so we need to update it
942 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800943 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700944 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
945 mDesiredActiveConfig = info;
946 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800947
948 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949 // This will trigger HWC refresh without resetting the idle timer.
950 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700951 // Start receiving vsync samples now, so that we can detect a period
952 // switch.
953 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700954 // As we called to set period, we will call to onRefreshRateChangeCompleted once
955 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700956 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700957 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700958 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800959 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700961
962 if (mRefreshRateOverlay) {
963 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
964 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965}
966
967status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
968 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800969
970 std::vector<int32_t> allowedConfig;
971 allowedConfig.push_back(mode);
972
973 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974}
975
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976void SurfaceFlinger::setActiveConfigInternal() {
977 ATRACE_CALL();
978
Dominik Laskowski22488f62019-03-28 09:53:04 -0700979 const auto display = getDefaultDisplayDeviceLocked();
980 if (!display) {
981 return;
982 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983
Dominik Laskowski22488f62019-03-28 09:53:04 -0700984 std::lock_guard<std::mutex> lock(mActiveConfigLock);
985 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
986
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987 display->setActiveConfig(mUpcomingActiveConfig.configId);
988
Alec Mouri754c98a2019-03-18 18:53:42 -0700989 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700990 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700992
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800993 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800994 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
995 mUpcomingActiveConfig.configId);
996 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997}
998
Ady Abraham53852a52019-05-28 18:07:44 -0700999void SurfaceFlinger::desiredActiveConfigChangeDone() {
1000 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1001 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1002 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001003
1004 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1005 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001006 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001007}
1008
Dominik Laskowski22488f62019-03-28 09:53:04 -07001009bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001010 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001012 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001014 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 return true;
1016 }
1017
1018 // We received the present fence from the HWC, so we assume it successfully updated
1019 // the config, hence we update SF.
1020 mCheckPendingFence = false;
1021 setActiveConfigInternal();
1022 }
1023
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 // Store the local variable to release the lock.
1025 ActiveConfigInfo desiredActiveConfig;
1026 {
1027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (!mDesiredActiveConfigChanged) {
1029 return false;
1030 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 desiredActiveConfig = mDesiredActiveConfig;
1032 }
1033
Dominik Laskowski22488f62019-03-28 09:53:04 -07001034 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1036 // display is not valid or we are already in the requested mode
1037 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001038 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001040 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041
Ady Abraham838de062019-02-04 10:24:03 -08001042 // Desired active config was set, it is different than the config currently in use, however
1043 // allowed configs might have change by the time we process the refresh.
1044 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001045 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001046 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001047 return false;
1048 }
Alec Mouri7f015182019-07-11 13:56:22 -07001049
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050 mUpcomingActiveConfig = desiredActiveConfig;
1051 const auto displayId = display->getId();
1052 LOG_ALWAYS_FATAL_IF(!displayId);
1053
1054 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1055 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1056
1057 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001059 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001061}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1064 Vector<ColorMode>* outColorModes) {
1065 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001066 return BAD_VALUE;
1067 }
1068
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001070 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001071 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001072 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1073
1074 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1075 if (!displayId) {
1076 return NAME_NOT_FOUND;
1077 }
1078
Dominik Laskowski075d3172018-05-24 15:50:06 -07001079 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001080 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001081 }
Michael Wright28f24d02016-07-12 13:30:53 -07001082 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001083
1084 // If it's built-in display and the configuration claims it's not wide color capable,
1085 // filter out all wide color modes. The typical reason why this happens is that the
1086 // hardware is not good enough to support GPU composition of wide color, and thus the
1087 // OEMs choose to disable this capability.
1088 if (isInternalDisplay && !hasWideColorDisplay) {
1089 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1090 isWideColorMode);
1091 } else {
1092 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1093 }
Michael Wright28f24d02016-07-12 13:30:53 -07001094
1095 return NO_ERROR;
1096}
1097
Daniel Solomon42d04562019-01-20 21:03:19 -08001098status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1099 ui::DisplayPrimaries &primaries) {
1100 if (!displayToken) {
1101 return BAD_VALUE;
1102 }
1103
1104 // Currently we only support this API for a single internal display.
1105 if (getInternalDisplayToken() != displayToken) {
1106 return BAD_VALUE;
1107 }
1108
1109 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1110 return NO_ERROR;
1111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1114 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001115 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001116 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001117 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001118}
1119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001121 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 Vector<ColorMode> modes;
1123 getDisplayColorModes(displayToken, &modes);
1124 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1125 if (mode < ColorMode::NATIVE || !exists) {
1126 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1127 decodeColorMode(mode).c_str(), mode, displayToken.get());
1128 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001129 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130 const auto display = getDisplayDevice(displayToken);
1131 if (!display) {
1132 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1133 decodeColorMode(mode).c_str(), mode, displayToken.get());
1134 } else if (display->isVirtual()) {
1135 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1136 decodeColorMode(mode).c_str(), mode);
1137 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001138 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
Lloyd Piquef5275482019-01-29 18:42:42 -08001139 RenderIntent::COLORIMETRIC,
1140 Dataspace::UNKNOWN);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141 }
1142 }));
1143
Michael Wright28f24d02016-07-12 13:30:53 -07001144 return NO_ERROR;
1145}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001146
Svetoslavd85084b2014-03-20 10:28:31 -07001147status_t SurfaceFlinger::clearAnimationFrameStats() {
1148 Mutex::Autolock _l(mStateLock);
1149 mAnimFrameTracker.clearStats();
1150 return NO_ERROR;
1151}
1152
1153status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1154 Mutex::Autolock _l(mStateLock);
1155 mAnimFrameTracker.getStats(outStats);
1156 return NO_ERROR;
1157}
1158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1160 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001161 Mutex::Autolock _l(mStateLock);
1162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163 const auto display = getDisplayDeviceLocked(displayToken);
1164 if (!display) {
1165 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001166 return BAD_VALUE;
1167 }
1168
Peiyong Linfb069302018-04-25 14:34:31 -07001169 // At this point the DisplayDeivce should already be set up,
1170 // meaning the luminance information is already queried from
1171 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001172 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001173 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1174 capabilities.getDesiredMaxLuminance(),
1175 capabilities.getDesiredMaxAverageLuminance(),
1176 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001177
1178 return NO_ERROR;
1179}
1180
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001181status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1182 ui::PixelFormat* outFormat,
1183 ui::Dataspace* outDataspace,
1184 uint8_t* outComponentMask) const {
1185 if (!outFormat || !outDataspace || !outComponentMask) {
1186 return BAD_VALUE;
1187 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001188 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001189 if (!display || !display->getId()) {
1190 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1191 return BAD_VALUE;
1192 }
1193 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1194 outDataspace, outComponentMask);
1195}
1196
Kevin DuBois74e53772018-11-19 10:52:38 -08001197status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1198 bool enable, uint8_t componentMask,
1199 uint64_t maxFrames) const {
1200 const auto display = getDisplayDevice(displayToken);
1201 if (!display || !display->getId()) {
1202 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1203 return BAD_VALUE;
1204 }
1205
1206 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1207 componentMask, maxFrames);
1208}
1209
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001210status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1211 uint64_t maxFrames, uint64_t timestamp,
1212 DisplayedFrameStats* outStats) const {
1213 const auto display = getDisplayDevice(displayToken);
1214 if (!display || !display->getId()) {
1215 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1216 return BAD_VALUE;
1217 }
1218
1219 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1220 outStats);
1221}
1222
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001223status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1224 if (!outSupported) {
1225 return BAD_VALUE;
1226 }
1227 *outSupported = getRenderEngine().supportsProtectedContent();
1228 return NO_ERROR;
1229}
1230
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001231status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1232 bool* outIsWideColorDisplay) const {
1233 if (!displayToken || !outIsWideColorDisplay) {
1234 return BAD_VALUE;
1235 }
1236 Mutex::Autolock _l(mStateLock);
1237 const auto display = getDisplayDeviceLocked(displayToken);
1238 if (!display) {
1239 return BAD_VALUE;
1240 }
Peiyong Linff84a152019-05-17 18:36:19 -07001241
1242 // Use hasWideColorDisplay to override built-in display.
1243 const auto displayId = display->getId();
1244 if (displayId && displayId == getInternalDisplayIdLocked()) {
1245 *outIsWideColorDisplay = hasWideColorDisplay;
1246 return NO_ERROR;
1247 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001248 *outIsWideColorDisplay = display->hasWideColorGamut();
1249 return NO_ERROR;
1250}
1251
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001252status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001253 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 if (mInjectVSyncs == enable) {
1257 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259
Ana Krulecc2870422019-01-29 19:00:58 -08001260 auto resyncCallback =
1261 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001263 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001264 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 if (enable) {
1266 ALOGV("VSync Injections enabled");
1267 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001268 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001269 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001271 impl::EventThread::InterceptVSyncsCallback(),
1272 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 } else {
1276 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001277 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1278 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001279 }
1280
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001281 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001282 }));
1283
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001284 return NO_ERROR;
1285}
1286
1287status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001288 Mutex::Autolock _l(mStateLock);
1289
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001290 if (!mInjectVSyncs) {
1291 ALOGE("VSync Injections not enabled");
1292 return BAD_VALUE;
1293 }
1294 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1295 ALOGV("Injecting VSync inside SurfaceFlinger");
1296 mVSyncInjector->onInjectSyncEvent(when);
1297 }
1298 return NO_ERROR;
1299}
1300
Lloyd Pique755e3192018-01-31 16:46:15 -08001301status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1302 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001303 // Try to acquire a lock for 1s, fail gracefully
1304 const status_t err = mStateLock.timedLock(s2ns(1));
1305 const bool locked = (err == NO_ERROR);
1306 if (!locked) {
1307 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1308 return TIMED_OUT;
1309 }
1310
1311 outLayers->clear();
1312 mCurrentState.traverseInZOrder([&](Layer* layer) {
1313 outLayers->push_back(layer->getLayerDebugInfo());
1314 });
1315
1316 mStateLock.unlock();
1317 return NO_ERROR;
1318}
1319
Peiyong Linc6780972018-10-28 15:24:08 -07001320status_t SurfaceFlinger::getCompositionPreference(
1321 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1322 Dataspace* outWideColorGamutDataspace,
1323 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001324 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001325 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001326 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001327 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001328 return NO_ERROR;
1329}
1330
Dan Stozaec460082018-12-17 15:35:09 -08001331status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1332 const sp<IBinder>& stopLayerHandle,
1333 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001334 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001335 return BAD_VALUE;
1336 }
1337 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001338 return NO_ERROR;
1339}
1340
Dan Stozaec460082018-12-17 15:35:09 -08001341status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001342 if (!listener) {
1343 return BAD_VALUE;
1344 }
Dan Stozaec460082018-12-17 15:35:09 -08001345 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001346 return NO_ERROR;
1347}
Dan Gittik57e63c52019-01-18 16:37:54 +00001348
1349status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1350 bool* outSupport) const {
1351 if (!displayToken || !outSupport) {
1352 return BAD_VALUE;
1353 }
1354 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1355 if (!displayId) {
1356 return NAME_NOT_FOUND;
1357 }
1358 *outSupport =
1359 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1360 return NO_ERROR;
1361}
1362
1363status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1364 float brightness) const {
1365 if (!displayToken) {
1366 return BAD_VALUE;
1367 }
1368 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1369 if (!displayId) {
1370 return NAME_NOT_FOUND;
1371 }
1372 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1373}
1374
Ady Abraham8532d012019-05-08 14:50:56 -07001375status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1376 PowerHint powerHint = static_cast<PowerHint>(hintId);
1377
1378 if (powerHint == PowerHint::INTERACTION) {
1379 mScheduler->notifyTouchEvent();
1380 }
1381
1382 return NO_ERROR;
1383}
1384
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001385// ----------------------------------------------------------------------------
1386
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001387sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001388 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001389 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001390 Mutex::Autolock lock(mStateLock);
1391 return getVsyncPeriod();
1392 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001393
Ana Krulecc2870422019-01-29 19:00:58 -08001394 const auto& handle =
1395 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001396
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001397 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1398 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001399}
1400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001402
1403void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001404 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001405}
1406
1407void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001408 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001409 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001410}
1411
1412void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001413 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001414 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001415}
1416
1417void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001418 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001419 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001420}
1421
1422status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001423 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001424 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001425}
1426
1427status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001428 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001429 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001430 if (res == NO_ERROR) {
1431 msg->wait();
1432 }
1433 return res;
1434}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001435
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001436void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001437 do {
1438 waitForEvent();
1439 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001440}
1441
Dominik Laskowski83b88212018-12-11 13:34:06 -08001442nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001443 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001444 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1445 return 0;
1446 }
1447
1448 const auto config = getHwComposer().getActiveConfig(*displayId);
1449 return config ? config->getVsyncPeriod() : 0;
1450}
1451
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001452void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1453 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001454 ATRACE_NAME("SF onVsync");
1455
Steven Thomas3cfac282017-02-06 12:29:30 -08001456 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001458 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 return;
1460 }
1461
Dominik Laskowski075d3172018-05-24 15:50:06 -07001462 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001463 return;
1464 }
1465
Dominik Laskowski075d3172018-05-24 15:50:06 -07001466 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001467 // For now, we don't do anything with external display vsyncs.
1468 return;
1469 }
1470
Alec Mourif8e689c2019-05-20 18:32:22 -07001471 bool periodFlushed = false;
1472 mScheduler->addResyncSample(timestamp, &periodFlushed);
1473 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001474 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001475 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001476}
1477
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001479 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1480 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481}
1482
Ady Abraham261614e2019-07-10 17:53:12 -07001483bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001484 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001485}
1486
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001487void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001488 const auto display = getDefaultDisplayDeviceLocked();
1489 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001490 return;
1491 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001492 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001493
Ana Krulec7d1d6832018-12-27 11:10:09 -08001494 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001495 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001496 if (!refreshRateConfig) {
1497 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001498 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001499 }
Ady Abraham1902d072019-03-01 17:18:59 -08001500
Alec Mouri0a1cc962019-03-14 12:33:02 -07001501 const int desiredConfigId = refreshRateConfig->configId;
1502
Dominik Laskowski22488f62019-03-28 09:53:04 -07001503 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001504 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1505 return;
1506 }
1507
Dominik Laskowski22488f62019-03-28 09:53:04 -07001508 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001509}
1510
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001511void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001512 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001514 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001515
Lloyd Piqueba04e622017-12-14 17:11:26 -08001516 // Ignore events that do not have the right sequenceId.
1517 if (sequenceId != getBE().mComposerSequenceId) {
1518 return;
1519 }
1520
Steven Thomasb02664d2017-07-26 18:48:28 -07001521 // Only lock if we're not on the main thread. This function is normally
1522 // called on a hwbinder thread, but for the primary display it's called on
1523 // the main thread with the state lock already held, so don't attempt to
1524 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001525 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001526
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001527 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001528
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001529 if (std::this_thread::get_id() == mMainThreadId) {
1530 // Process all pending hot plug events immediately if we are on the main thread.
1531 processDisplayHotplugEventsLocked();
1532 }
1533
Lloyd Piqueba04e622017-12-14 17:11:26 -08001534 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001535}
1536
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001537void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001538 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001539 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001540 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001541 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001542 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001543}
1544
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001545void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001546 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001547
1548 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1549 // display power state.
1550 postMessageAsync(new LambdaMessage(
1551 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1552}
1553
1554void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1555 ATRACE_CALL();
1556
Ady Abraham27c70212019-06-11 10:52:26 -07001557 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1558
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001559 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001560 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1561 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001562 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001563 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001564 }
Mathias Agopian86303202012-07-24 22:46:10 -07001565}
1566
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001568void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001569 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570 // Clear the drawing state so that the logic inside of
1571 // handleTransactionLocked will fire. It will determine the delta between
1572 // mCurrentState and mDrawingState and re-apply all changes when we make the
1573 // transition.
1574 mDrawingState.displays.clear();
1575 mDisplays.clear();
1576}
1577
Steven Thomas050b2c82017-03-06 11:45:16 -08001578void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001579 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001580 if (!mVrFlinger)
1581 return;
1582 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001583 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001584 return;
1585 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001586
Lloyd Pique441d5042018-10-18 16:49:51 -07001587 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001588 ALOGE("Vr flinger is only supported for remote hardware composer"
1589 " service connections. Ignoring request to transition to vr"
1590 " flinger.");
1591 mVrFlingerRequestsDisplay = false;
1592 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001593 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001596
Steven Thomas0123ac62018-07-12 11:32:34 -07001597 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001598 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001599
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001600 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001601
1602 // Clear out all the output layers from the composition engine for all
1603 // displays before destroying the hardware composer interface. This ensures
1604 // any HWC layers are destroyed through that interface before it becomes
1605 // invalid.
1606 for (const auto& [token, displayDevice] : mDisplays) {
1607 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1608 compositionengine::Output::OutputLayers());
1609 }
1610
Steven Thomas0123ac62018-07-12 11:32:34 -07001611 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1612 // called below. Clear the reference now so we don't accidentally use it
1613 // later.
1614 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001615
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001617 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001618 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001619
Steven Thomasb02664d2017-07-26 18:48:28 -07001620 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001621 // Delete the current instance before creating the new one
1622 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1623 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1624 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1625 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001626
Lloyd Pique441d5042018-10-18 16:49:51 -07001627 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001628 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001629
1630 if (vrFlingerRequestsDisplay) {
1631 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001633
1634 mVisibleRegionsDirty = true;
1635 invalidateHwcGeometry();
1636
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001637 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001638 display = getDefaultDisplayDeviceLocked();
1639 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001640 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001641
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001643 const nsecs_t vsyncPeriod = getVsyncPeriod();
1644 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001645
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001646 // The present fences returned from vr_hwc are not an accurate
1647 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001648 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001649
Steven Thomasb02664d2017-07-26 18:48:28 -07001650 // Use phase of 0 since phase is not known.
1651 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001652 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001653 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001654
Ana Krulecc2870422019-01-29 19:00:58 -08001655 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001656
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001657 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001658 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001659}
1660
Ady Abrahambe0f9482019-04-24 15:41:53 -07001661bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1662 // We are storing the last 2 present fences. If sf's phase offset is to be
1663 // woken up before the actual vsync but targeting the next vsync, we need to check
1664 // fence N-2
1665 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001666 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001667 ? mPreviousPresentFences[0]
1668 : mPreviousPresentFences[1];
1669
1670 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1671}
1672
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001673void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001674 DisplayStatInfo stats;
1675 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001676 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001677 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001678 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001679 mPhaseOffsets->getOffsetThresholdForNextVsync()
1680 ? presentTime
1681 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001682}
1683
Dominik Laskowski22488f62019-03-28 09:53:04 -07001684void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001685 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001686 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001687 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001688 // calculate the expected present time once and use the cached
1689 // value throughout this frame to make sure all layers are
1690 // seeing this same value.
1691 populateExpectedPresentTime();
1692
Ady Abraham50204dd2019-07-19 15:47:11 -07001693 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1694 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1695 mHadDeviceComposition && frameMissed};
1696 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1697 mHadClientComposition && frameMissed};
1698
Alec Mouricc0fc602019-02-26 21:45:19 -08001699 if (frameMissed) {
1700 mFrameMissedCount++;
1701 mTimeStats->incrementMissedFrames();
1702 }
1703
Alec Mouri40189b02019-03-05 15:07:54 -08001704 if (hwcFrameMissed) {
1705 mHwcFrameMissedCount++;
1706 }
1707
1708 if (gpuFrameMissed) {
1709 mGpuFrameMissedCount++;
1710 }
1711
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001712 if (mUseSmart90ForVideo) {
1713 // This call is made each time SF wakes up and creates a new frame. It is part
1714 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001715 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001716 }
1717
Ady Abrahamb838aed2019-02-12 15:30:16 -08001718 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001719 break;
1720 }
1721
Ady Abraham4658e112019-07-22 13:07:26 -07001722 if (frameMissed && mPropagateBackpressure) {
1723 if ((hwcFrameMissed && !gpuFrameMissed) ||
1724 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001725 signalLayerUpdate();
1726 break;
1727 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001728 }
Dan Stoza50182882016-07-08 12:02:20 -07001729
Steven Thomas050b2c82017-03-06 11:45:16 -08001730 // Now that we're going to make it to the handleMessageTransaction()
1731 // call below it's safe to call updateVrFlinger(), which will
1732 // potentially trigger a display handoff.
1733 updateVrFlinger();
1734
Dan Stoza6b9454d2014-11-07 16:00:59 -08001735 bool refreshNeeded = handleMessageTransaction();
1736 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001737
1738 updateCursorAsync();
1739 updateInputFlinger();
1740
Dan Stoza58784442014-12-02 16:58:17 -08001741 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001742 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001743 // Signal a refresh if a transaction modified the window state,
1744 // a new buffer was latched, or if HWC has requested a full
1745 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001746 signalRefresh();
1747 }
1748 break;
1749 }
1750 case MessageQueue::REFRESH: {
1751 handleMessageRefresh();
1752 break;
1753 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001754 }
1755}
1756
Dan Stoza6b9454d2014-11-07 16:00:59 -08001757bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001758 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001759 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001760
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001761 bool flushedATransaction = flushTransactionQueues();
1762
1763 bool runHandleTransaction = transactionFlags &&
1764 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1765
1766 if (runHandleTransaction) {
1767 handleTransaction(eTransactionMask);
1768 } else {
1769 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001770 }
1771
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001772 if (transactionFlushNeeded()) {
1773 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001774 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001775
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001776 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001777}
1778
Mathias Agopian4fec8732012-06-29 14:12:52 -07001779void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001780 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001781
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001782 mRefreshPending = false;
1783
Lloyd Piqueab039b52019-02-13 14:22:42 -08001784 compositionengine::CompositionRefreshArgs refreshArgs;
1785 for (const auto& [_, display] : mDisplays) {
1786 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1787 }
1788 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1789 auto compositionLayer = layer->getCompositionLayer();
1790 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1791 });
1792
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001793 const bool repaintEverything = mRepaintEverything.exchange(false);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001794 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001795 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001796 calculateWorkingSet();
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001797 for (const auto& [token, displayDevice] : mDisplays) {
1798 auto display = displayDevice->getCompositionDisplay();
1799 display->beginFrame();
1800 display->prepareFrame();
1801 doDebugFlashRegions(displayDevice, repaintEverything);
1802 doComposition(displayDevice, repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001803 }
1804
David Sodmanfa9b2af2017-12-24 13:28:59 -08001805 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001806 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001807
Lloyd Pique66d68602019-02-13 14:23:31 -08001808 mHadClientComposition =
1809 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1810 auto& displayDevice = tokenDisplayPair.second;
1811 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1812 });
1813 mHadDeviceComposition =
1814 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1815 auto& displayDevice = tokenDisplayPair.second;
1816 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1817 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001819 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001820
David Sodman7e4ae112018-02-09 15:02:28 -08001821 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001822 if (mVisibleRegionsDirty) {
1823 mVisibleRegionsDirty = false;
1824 if (mTracingEnabled) {
1825 mTracing.notify("visibleRegionsDirty");
1826 }
1827 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001828
1829 if (mCompositionEngine->needsAnotherUpdate()) {
1830 signalLayerUpdate();
1831 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834
1835bool SurfaceFlinger::handleMessageInvalidate() {
1836 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001837 bool refreshNeeded = handlePageFlip();
1838
Vishnu Nair4351ad52019-02-11 14:13:02 -08001839 if (mVisibleRegionsDirty) {
1840 computeLayerBounds();
1841 }
1842
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001843 for (auto& layer : mLayersPendingRefresh) {
1844 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001845 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001846 invalidateLayerStack(layer, visibleReg);
1847 }
1848 mLayersPendingRefresh.clear();
1849 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001850}
1851
David Sodman79bba0e2018-08-05 18:07:49 -07001852void SurfaceFlinger::calculateWorkingSet() {
1853 ATRACE_CALL();
1854 ALOGV(__FUNCTION__);
1855
Lloyd Piquef5275482019-01-29 18:42:42 -08001856 const bool updatingGeometryThisFrame = mGeometryInvalid;
1857 mGeometryInvalid = false;
1858
Lloyd Pique05ed22e2019-08-09 12:20:51 -07001859 // Latch the frontend layer composition state for each layer being
1860 // composed.
1861 for (const auto& [token, displayDevice] : mDisplays) {
1862 auto display = displayDevice->getCompositionDisplay();
1863 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1864 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1865 updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001866 }
1867 }
1868
1869 if (CC_UNLIKELY(updatingGeometryThisFrame)) {
1870 for (const auto& [token, displayDevice] : mDisplays) {
1871 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquea83776c2019-01-29 18:42:32 -08001872 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001873
Lloyd Piquea83776c2019-01-29 18:42:32 -08001874 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquef5275482019-01-29 18:42:42 -08001875 // Assign a simple Z order sequence to each visible layer.
1876 layer->editState().z = zOrder++;
David Sodman79bba0e2018-08-05 18:07:49 -07001877 }
1878 }
1879 }
1880
Lloyd Piquef5275482019-01-29 18:42:42 -08001881 // Determine the color configuration of each output
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 for (const auto& [token, displayDevice] : mDisplays) {
1883 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001884
Lloyd Piquef5275482019-01-29 18:42:42 -08001885 ColorMode colorMode = ColorMode::NATIVE;
1886 Dataspace dataspace = Dataspace::UNKNOWN;
1887 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1888 if (useColorManagement) {
1889 pickColorMode(displayDevice, &colorMode, &dataspace, &renderIntent);
1890 }
1891 display->setColorMode(colorMode, dataspace, renderIntent, mColorSpaceAgnosticDataspace);
1892 }
1893
1894 for (const auto& [token, displayDevice] : mDisplays) {
1895 auto display = displayDevice->getCompositionDisplay();
1896
1897 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquec358b522019-08-09 12:21:21 -07001898 if (mDebugDisableHWC || mDebugRegion) {
1899 layer->editState().forceClientComposition = true;
1900 }
1901
Lloyd Piquef5275482019-01-29 18:42:42 -08001902 // Update the composition state of the output layer, as needed
1903 // recomputing it from the state given by the front-end layer.
1904 layer->updateCompositionState(updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001905
Lloyd Piquef5275482019-01-29 18:42:42 -08001906 // Send the updated state to the HWC, if appropriate.
1907 layer->writeStateToHWC(updatingGeometryThisFrame);
1908 }
1909 }
1910
1911 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1912 for (const auto& [token, displayDevice] : mDisplays) {
1913 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001914 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001915 }
Lloyd Piquef5275482019-01-29 18:42:42 -08001916 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001917 }
David Sodman79bba0e2018-08-05 18:07:49 -07001918}
1919
Lloyd Pique32cbe282018-10-19 13:09:22 -07001920void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1921 bool repaintEverything) {
1922 auto display = displayDevice->getCompositionDisplay();
1923 const auto& displayState = display->getState();
1924
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925 // is debugging enabled
1926 if (CC_LIKELY(!mDebugRegion))
1927 return;
1928
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001930 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001931 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001932 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001933 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001934 // redraw the whole screen
Lloyd Pique688abd42019-02-15 15:42:24 -08001935 display->composeSurfaces(dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001936
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001937 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 }
1939 }
1940
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001941 displayDevice->getCompositionDisplay()->postFramebuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001942
1943 if (mDebugRegion > 1) {
1944 usleep(mDebugRegion * 1000);
1945 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001946
Lloyd Pique66d68602019-02-13 14:23:31 -08001947 displayDevice->getCompositionDisplay()->prepareFrame();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948}
1949
Ana Krulece588e312018-09-18 12:32:24 -07001950void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1951 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952 // Update queue of past composite+present times and determine the
1953 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001956 while (!getBE().mCompositePresentTimes.empty()) {
1957 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 // Cached values should have been updated before calling this method,
1959 // which helps avoid duplicate syscalls.
1960 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1961 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1962 break;
1963 }
1964 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001965 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966 }
1967
1968 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001969 while (getBE().mCompositePresentTimes.size() > 16) {
1970 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971 }
1972
Ana Krulece588e312018-09-18 12:32:24 -07001973 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001974}
1975
Ana Krulece588e312018-09-18 12:32:24 -07001976void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1977 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Integer division and modulo round toward 0 not -inf, so we need to
1979 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001980 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1981 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1982 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983
Ana Krulec757f63a2019-01-25 10:46:18 -08001984 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001985 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001986 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001987 }
1988
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 // Snap the latency to a value that removes scheduling jitter from the
1990 // composition and present times, which often have >1ms of jitter.
1991 // Reducing jitter is important if an app attempts to extrapolate
1992 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001993 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001995 nsecs_t bias = stats.vsyncPeriod / 2;
1996 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1997 nsecs_t snappedCompositeToPresentLatency =
1998 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999
David Sodman99974d22017-11-28 12:04:33 -08002000 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002001 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2002 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002003 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002004}
2005
David Sodman2b406362017-12-15 13:33:47 -08002006void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ATRACE_CALL();
2009 ALOGV("postComposition");
2010
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002012 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002014 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 }
2016
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002017 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002018 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002022 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002024 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2025 ->getRenderSurface()
2026 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 } else {
2029 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2030 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031
David Sodman73beded2017-11-15 11:56:06 -08002032 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002033 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2034 mPreviousPresentFences[0] = displayDevice
2035 ? getHwComposer().getPresentFence(*displayDevice->getId())
2036 : Fence::NO_FENCE;
2037 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002038 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039
Ana Krulece588e312018-09-18 12:32:24 -07002040 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002041 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042
Lloyd Piqueab039b52019-02-13 14:22:42 -08002043 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2044 // be sampled a little later than when we started doing work for this frame,
2045 // but that should be okay since updateCompositorTiming has snapping logic.
2046 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2047 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002048 CompositorTiming compositorTiming;
2049 {
David Sodman99974d22017-11-28 12:04:33 -08002050 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2051 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002052 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053
Robert Carr2047fae2016-11-28 14:09:09 -08002054 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002055 bool frameLatched =
2056 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2057 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002058 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002059 recordBufferingStats(layer->getName().string(),
2060 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002061 }
Robert Carr2047fae2016-11-28 14:09:09 -08002062 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002063
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002064 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002065 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002066 }
2067
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002068 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2070 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002071 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002072 }
2073 }
2074
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002075 if (mAnimCompositionPending) {
2076 mAnimCompositionPending = false;
2077
Brian Anderson4e606e32017-03-16 15:34:57 -07002078 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002080 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002081 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082 // The HWC doesn't support present fences, so use the refresh
2083 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 const nsecs_t presentTime =
2085 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002086 mAnimFrameTracker.setActualPresentTime(presentTime);
2087 }
2088 mAnimFrameTracker.advanceFrame();
2089 }
Dan Stozab90cf072015-03-05 11:05:59 -08002090
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002091 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002092 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002093 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002094 }
2095
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002096 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002097
Lloyd Pique32cbe282018-10-19 13:09:22 -07002098 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2099 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002100 return;
2101 }
2102
2103 nsecs_t currentTime = systemTime();
2104 if (mHasPoweredOff) {
2105 mHasPoweredOff = false;
2106 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002107 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002108 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002109 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2110 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002111 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002112 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002113 }
David Sodman4a36e932017-11-07 14:29:47 -08002114 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002115 }
David Sodman4a36e932017-11-07 14:29:47 -08002116 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002117
2118 {
2119 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002120 if (mTexturePool.size() < mTexturePoolSize) {
2121 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002122 const size_t offset = mTexturePool.size();
2123 mTexturePool.resize(mTexturePoolSize);
2124 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2125 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002126 } else if (mTexturePool.size() > mTexturePoolSize) {
2127 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2128 const size_t offset = mTexturePoolSize;
2129 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2130 mTexturePool.resize(mTexturePoolSize);
2131 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002132 }
2133 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002134
Ady Abrahambe0f9482019-04-24 15:41:53 -07002135 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002136 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002137
Kevin DuBois413287f2019-02-25 08:46:47 -08002138 if (mLumaSampling && mRegionSamplingThread) {
2139 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002140 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002141
2142 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2143 // side-effect of getTotalSize(), so we check that again here
2144 if (ATRACE_ENABLED()) {
2145 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2146 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002147}
2148
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149void SurfaceFlinger::computeLayerBounds() {
2150 for (const auto& pair : mDisplays) {
2151 const auto& displayDevice = pair.second;
2152 const auto display = displayDevice->getCompositionDisplay();
2153 for (const auto& layer : mDrawingState.layersSortedByZ) {
2154 // only consider the layers on the given layer stack
2155 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002156 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002157 }
2158
2159 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2160 }
2161 }
2162}
2163
Mathias Agopiancd60f992012-08-16 16:28:27 -07002164void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 ATRACE_CALL();
2166 ALOGV("rebuildLayerStacks");
2167
Mathias Agopiancd60f992012-08-16 16:28:27 -07002168 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002169 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002170 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002171 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002172
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002173 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002174 const auto& displayDevice = pair.second;
2175 auto display = displayDevice->getCompositionDisplay();
2176 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002177 Region opaqueRegion;
2178 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002179 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002180 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002181 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002182 const ui::Transform& tr = displayState.transform;
2183 const Rect bounds = displayState.bounds;
2184 if (displayState.isEnabled) {
2185 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002186
Jeff Sharkey76488112017-02-27 14:15:18 -07002187 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002188 auto compositionLayer = layer->getCompositionLayer();
2189 if (compositionLayer == nullptr) {
2190 return;
2191 }
2192
Lloyd Pique32cbe282018-10-19 13:09:22 -07002193 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002194 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2195 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2196
Lloyd Pique07e33212018-12-18 16:33:37 -08002197 bool needsOutputLayer = false;
2198
Lloyd Piqueef36b002019-01-23 17:52:04 -08002199 if (display->belongsInOutput(layer->getLayerStack(),
2200 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002201 Region drawRegion(tr.transform(
2202 layer->visibleNonTransparentRegion));
2203 drawRegion.andSelf(bounds);
2204 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002205 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002206 }
Chia-I Wu83806892017-11-16 10:50:20 -08002207 }
2208
Lloyd Pique07e33212018-12-18 16:33:37 -08002209 if (needsOutputLayer) {
2210 layersSortedByZ.emplace_back(
2211 display->getOrCreateOutputLayer(displayId, compositionLayer,
2212 layerFE));
2213 deprecated_layersSortedByZ.add(layer);
2214
2215 auto& outputLayerState = layersSortedByZ.back()->editState();
2216 outputLayerState.visibleRegion =
2217 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2218 } else if (displayId) {
2219 // For layers that are being removed from a HWC display,
2220 // and that have queued frames, add them to a a list of
2221 // released layers so we can properly set a fence.
2222 bool hasExistingOutputLayer =
2223 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2224 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2225 mLayersWithQueuedFrames.cend(),
2226 layer) != mLayersWithQueuedFrames.cend();
2227
2228 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002229 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002230 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002231 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002232 });
2233 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002234
2235 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002236 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002237
2238 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002239
2240 Region undefinedRegion{bounds};
2241 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2242
2243 display->editState().undefinedRegion = undefinedRegion;
2244 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002245 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002246 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002247}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002248
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002249// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002251// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002253// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002254// The returned HDR data space is one of
2255// - Dataspace::UNKNOWN
2256// - Dataspace::BT2020_HLG
2257// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002258Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2259 Dataspace* outHdrDataSpace,
2260 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002261 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002262 *outHdrDataSpace = Dataspace::UNKNOWN;
2263
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002264 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002265 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266 case Dataspace::V0_SCRGB:
2267 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002268 case Dataspace::BT2020:
2269 case Dataspace::BT2020_ITU:
2270 case Dataspace::BT2020_LINEAR:
2271 case Dataspace::DISPLAY_BT2020:
2272 bestDataSpace = Dataspace::DISPLAY_BT2020;
2273 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002275 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277 case Dataspace::BT2020_PQ:
2278 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002279 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280 *outHdrDataSpace = Dataspace::BT2020_PQ;
Lloyd Piquef5275482019-01-29 18:42:42 -08002281 *outIsHdrClientComposition =
2282 layer->getCompositionLayer()->getState().frontEnd.forceClientComposition;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002284 case Dataspace::BT2020_HLG:
2285 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002286 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 // When there's mixed PQ content and HLG content, we set the HDR
2288 // data space to be BT2020_PQ and convert HLG to PQ.
2289 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2290 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002291 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002292 break;
2293 default:
2294 break;
2295 }
Romain Guy54f154a2017-10-24 21:40:32 +01002296 }
2297
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002299}
2300
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2303 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2305 *outMode = ColorMode::NATIVE;
2306 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002309 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002310
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002312 bool isHdrClientComposition = false;
2313 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002315 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2316
Peiyong Lina3ea5592019-02-10 14:45:00 -08002317 switch (mForceColorMode) {
2318 case ColorMode::SRGB:
2319 bestDataSpace = Dataspace::V0_SRGB;
2320 break;
2321 case ColorMode::DISPLAY_P3:
2322 bestDataSpace = Dataspace::DISPLAY_P3;
2323 break;
2324 default:
2325 break;
2326 }
2327
Peiyong Lindfde5112018-06-05 10:58:41 -07002328 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002329 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2330 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002331 if (isHdr) {
2332 bestDataSpace = hdrDataSpace;
2333 }
2334
Chia-I Wu0d711262018-05-21 15:19:35 -07002335 RenderIntent intent;
2336 switch (mDisplayColorSetting) {
2337 case DisplayColorSetting::MANAGED:
2338 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002339 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002340 break;
2341 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002342 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002343 break;
2344 default: // vendor display color setting
2345 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2346 break;
2347 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002348
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002349 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002350}
2351
Lloyd Pique32cbe282018-10-19 13:09:22 -07002352void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002353 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354 ALOGV("doComposition");
2355
Lloyd Pique32cbe282018-10-19 13:09:22 -07002356 auto display = displayDevice->getCompositionDisplay();
2357 const auto& displayState = display->getState();
2358
2359 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002361 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002362
David Sodmanfa9b2af2017-12-24 13:28:59 -08002363 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002364 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002365
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002367 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002368 }
Lloyd Pique35fca9d2019-02-13 14:24:11 -08002369 displayDevice->getCompositionDisplay()->postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370}
2371
David Sodmanfa9b2af2017-12-24 13:28:59 -08002372void SurfaceFlinger::postFrame()
2373{
2374 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002375 const auto display = getDefaultDisplayDeviceLocked();
2376 if (display && getHwComposer().isConnected(*display->getId())) {
2377 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002378 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2379 logFrameStats();
2380 }
2381 }
2382}
2383
Mathias Agopian87baae12012-07-31 12:38:26 -07002384void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002385{
Mathias Agopian841cde52012-03-01 15:44:37 -08002386 ATRACE_CALL();
2387
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002388 // here we keep a copy of the drawing state (that is the state that's
2389 // going to be overwritten by handleTransactionLocked()) outside of
2390 // mStateLock so that the side-effects of the State assignment
2391 // don't happen with mStateLock held (which can cause deadlocks).
2392 State drawingState(mDrawingState);
2393
Mathias Agopianca4d3602011-05-19 15:38:14 -07002394 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002395 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396
Mathias Agopianca4d3602011-05-19 15:38:14 -07002397 // Here we're guaranteed that some transaction flags are set
2398 // so we can call handleTransactionLocked() unconditionally.
2399 // We call getTransactionFlags(), which will also clear the flags,
2400 // with mStateLock held to guarantee that mCurrentState won't change
2401 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002402
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002403 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002404 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002405 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002406
Mathias Agopianca4d3602011-05-19 15:38:14 -07002407 mDebugInTransaction = 0;
2408 invalidateHwcGeometry();
2409 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002410}
2411
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2413 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 const std::optional<DisplayIdentificationInfo> info =
2415 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416
Dominik Laskowski075d3172018-05-24 15:50:06 -07002417 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002418 continue;
2419 }
2420
Lloyd Piqueba04e622017-12-14 17:11:26 -08002421 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002423 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 mPhysicalDisplayTokens[info->id] = new BBinder();
2425 DisplayDeviceState state;
2426 state.displayId = info->id;
2427 state.isSecure = true; // All physical displays are currently considered secure.
2428 state.displayName = info->name;
2429 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2430 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002431 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002432 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002433 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2436 if (index >= 0) {
2437 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2438 mInterceptor->saveDisplayDeletion(state.sequenceId);
2439 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002440 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002442 }
2443
2444 processDisplayChangesLocked();
2445 }
2446
2447 mPendingHotplugEvents.clear();
2448}
2449
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002450void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002451 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2452 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002453}
2454
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002456 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002457 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 const sp<IGraphicBufferProducer>& producer) {
2459 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002460 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002462 creationArgs.isSecure = state.isSecure;
2463 creationArgs.displaySurface = dispSurface;
2464 creationArgs.hasWideColorGamut = false;
2465 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002466 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002467
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002468 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 creationArgs.isPrimary = isInternalDisplay;
2470
2471 if (useColorManagement && displayId) {
2472 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002474 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002475 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002477
Dominik Laskowski7e045462018-05-30 13:02:02 -07002478 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002479 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002480 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002481 }
tangrobin6753a022018-08-10 10:58:54 +08002482 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483
Dominik Laskowski075d3172018-05-24 15:50:06 -07002484 if (displayId) {
2485 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002488 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489
Lloyd Pique90c115d2018-09-18 21:39:42 -07002490 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002491 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002492 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 // Make sure that composition can never be stalled by a virtual display
2495 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002496 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002497 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2499 }
2500
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 creationArgs.displayInstallOrientation =
2502 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002503
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
Lloyd Pique90c115d2018-09-18 21:39:42 -07002507 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508
2509 if (maxFrameBufferAcquiredBuffers >= 3) {
2510 nativeWindowSurface->preallocateBuffers();
2511 }
2512
2513 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002514 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002515 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002517 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002519 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
Lloyd Piquef5275482019-01-29 18:42:42 -08002520 RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521 if (!state.isVirtual()) {
2522 LOG_ALWAYS_FATAL_IF(!displayId);
2523 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002524 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002526 display->setLayerStack(state.layerStack);
2527 display->setProjection(state.orientation, state.viewport, state.frame);
2528 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531}
2532
Lloyd Pique347200f2017-12-14 17:00:15 -08002533void SurfaceFlinger::processDisplayChangesLocked() {
2534 // here we take advantage of Vector's copy-on-write semantics to
2535 // improve performance by skipping the transaction entirely when
2536 // know that the lists are identical
2537 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2538 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2539 if (!curr.isIdenticalTo(draw)) {
2540 mVisibleRegionsDirty = true;
2541 const size_t cc = curr.size();
2542 size_t dc = draw.size();
2543
2544 // find the displays that were removed
2545 // (ie: in drawing state but not in current state)
2546 // also handle displays that changed
2547 // (ie: displays that are in both lists)
2548 for (size_t i = 0; i < dc;) {
2549 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2550 if (j < 0) {
2551 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002553 // Save display ID before disconnecting.
2554 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002555 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002556
2557 if (!display->isVirtual()) {
2558 LOG_ALWAYS_FATAL_IF(!displayId);
2559 dispatchDisplayHotplugEvent(displayId->value, false);
2560 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002561 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002562
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002563 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 } else {
2565 // this display is in both lists. see if something changed.
2566 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002567 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2569 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2570 if (state_binder != draw_binder) {
2571 // changing the surface is like destroying and
2572 // recreating the DisplayDevice, so we just remove it
2573 // from the drawing state, so that it get re-added
2574 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002575 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002576 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002577 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002578 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 mDrawingState.displays.removeItemsAt(i);
2580 dc--;
2581 // at this point we must loop to the next item
2582 continue;
2583 }
2584
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002585 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002587 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002588 }
2589 if ((state.orientation != draw[i].orientation) ||
2590 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002591 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 }
2593 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002594 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 }
2596 }
2597 }
2598 ++i;
2599 }
2600
2601 // find displays that were added
2602 // (ie: in current state but not in drawing state)
2603 for (size_t i = 0; i < cc; i++) {
2604 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2605 const DisplayDeviceState& state(curr[i]);
2606
Lloyd Pique542307f2018-10-19 13:24:08 -07002607 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 sp<IGraphicBufferProducer> producer;
2609 sp<IGraphicBufferProducer> bqProducer;
2610 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002611 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002612
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002614 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002615 // Virtual displays without a surface are dormant:
2616 // they have external state (layer stack, projection,
2617 // etc.) but no internal state (i.e. a DisplayDevice).
2618 if (state.surface != nullptr) {
2619 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 int width = 0;
2622 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2623 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2624 int height = 0;
2625 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2626 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2627 int intFormat = 0;
2628 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2629 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002630 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002631
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 displayId =
2633 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 }
2635
2636 // TODO: Plumb requested format back up to consumer
2637
2638 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002640 bqProducer, bqConsumer,
2641 state.displayName);
2642
2643 dispSurface = vds;
2644 producer = vds;
2645 }
2646 } else {
2647 ALOGE_IF(state.surface != nullptr,
2648 "adding a supported display, but rendering "
2649 "surface is provided (%p), ignoring it",
2650 state.surface.get());
2651
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 displayId = state.displayId;
2653 LOG_ALWAYS_FATAL_IF(!displayId);
2654 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 producer = bqProducer;
2656 }
2657
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002661 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002663 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002665 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 }
2667 }
2668 }
2669 }
2670 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002671
2672 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002673}
2674
Mathias Agopian87baae12012-07-31 12:38:26 -07002675void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002676{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002677 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2678
Dan Stoza7dde5992015-05-22 09:51:44 -07002679 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002680 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2681 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002682 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002683
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 /*
2685 * Traversal of the children
2686 * (perform the transaction for each of them if needed)
2687 */
2688
Marissa Wall06255332019-03-27 13:48:27 -07002689 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002690 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002692 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693
2694 const uint32_t flags = layer->doTransaction(0);
2695 if (flags & Layer::eVisibleRegion)
2696 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002697
2698 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002699 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002700 }
Robert Carr2047fae2016-11-28 14:09:09 -08002701 });
Marissa Wall06255332019-03-27 13:48:27 -07002702 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 }
2704
2705 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707 */
2708
Mathias Agopiane57f2922012-08-09 16:29:12 -07002709 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002711 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002714 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002715 // The transform hint might have changed for some layers
2716 // (either because a display has changed, or because a layer
2717 // as changed).
2718 //
2719 // Walk through all the layers in currentLayers,
2720 // and update their transform hint.
2721 //
2722 // If a layer is visible only on a single display, then that
2723 // display is used to calculate the hint, otherwise we use the
2724 // default display.
2725 //
2726 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2727 // the hint is set before we acquire a buffer from the surface texture.
2728 //
2729 // NOTE: layer transactions have taken place already, so we use their
2730 // drawing state. However, SurfaceFlinger's own transaction has not
2731 // happened yet, so we must use the current state layer list
2732 // (soon to become the drawing state list).
2733 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002735 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002736 bool first = true;
2737 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002738 // NOTE: we rely on the fact that layers are sorted by
2739 // layerStack first (so we don't have to traverse the list
2740 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002742 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002743 currentlayerStack = layerStack;
2744 // figure out if this layerstack is mirrored
2745 // (more than one display) if so, pick the default display,
2746 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002747 hintDisplay = nullptr;
2748 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002749 if (display->getCompositionDisplay()
2750 ->belongsInOutput(layer->getLayerStack(),
2751 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002752 if (hintDisplay) {
2753 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002754 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002755 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002756 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002757 }
2758 }
2759 }
2760 }
Chet Haase91d25932013-04-11 15:24:55 -07002761
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002762 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002763 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2764 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002765
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002766 // could be null when this layer is using a layerStack
2767 // that is not visible on any display. Also can occur at
2768 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002770 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002771
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002772 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002773 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 if (hintDisplay) {
2775 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002776 }
Robert Carr2047fae2016-11-28 14:09:09 -08002777
2778 first = false;
2779 });
Mathias Agopian84300952012-11-21 16:02:13 -08002780 }
2781
2782
Mathias Agopian3559b072012-08-15 13:46:03 -07002783 /*
2784 * Perform our own transaction if needed
2785 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786
2787 if (mLayersAdded) {
2788 mLayersAdded = false;
2789 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002790 mVisibleRegionsDirty = true;
2791 }
2792
2793 // some layers might have been removed, so
2794 // we need to update the regions they're exposing.
2795 if (mLayersRemoved) {
2796 mLayersRemoved = false;
2797 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002798 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002800 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002801 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002802 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002803 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002804 }
Robert Carr2047fae2016-11-28 14:09:09 -08002805 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 }
2807
Vishnu Nairec0ab382019-02-13 15:32:56 -08002808 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002810}
2811
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002812void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002813 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002814 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002815 return;
2816 }
2817
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002818 if (mVisibleRegionsDirty || mInputInfoChanged) {
2819 mInputInfoChanged = false;
2820 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002821 } else if (mInputWindowCommands.syncInputWindows) {
2822 // If the caller requested to sync input windows, but there are no
2823 // changes to input windows, notify immediately.
2824 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002825 }
2826
2827 executeInputWindowCommands();
2828}
2829
2830void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002831 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002832
2833 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2834 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002835 // When calculating the screen bounds we ignore the transparent region since it may
2836 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002837 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002838 }
2839 });
chaviw291d88a2019-02-14 10:33:58 -08002840
2841 mInputFlinger->setInputWindows(inputHandles,
2842 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2843 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002844}
2845
Vishnu Nairec0ab382019-02-13 15:32:56 -08002846void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002847 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002848 mPendingInputWindowCommands.clear();
2849}
2850
chaviwfbe5d9c2018-12-26 12:23:37 -08002851void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002852 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2853 if (transferTouchFocusCommand.fromToken != nullptr &&
2854 transferTouchFocusCommand.toToken != nullptr &&
2855 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2856 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2857 transferTouchFocusCommand.toToken);
2858 }
2859 }
2860
2861 mInputWindowCommands.clear();
2862}
2863
Riley Andrews03414a12014-07-01 14:22:59 -07002864void SurfaceFlinger::updateCursorAsync()
2865{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002867 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002868 continue;
2869 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2872 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002873 }
2874 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002875}
2876
2877void SurfaceFlinger::commitTransaction()
2878{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002879 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 for (const auto& l : mLayersPendingRemoval) {
2882 recordBufferingStats(l->getName().string(),
2883 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002884
Lloyd Pique07e33212018-12-18 16:33:37 -08002885 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002886 if (l->isRemovedFromCurrentState()) {
chaviw49a108c2019-08-12 11:23:06 -07002887 l->latchAndReleaseBuffer();
Robert Carr2e102c92018-10-23 12:11:15 -07002888 }
chaviw74d90ad2019-04-26 14:45:26 -07002889
2890 // If the layer has been removed and has no parent, then it will not be reachable
2891 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2892 // ensure we can copy its current to drawing state.
2893 if (!l->getParent()) {
2894 mOffscreenLayers.emplace(l.get());
2895 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 }
2897 mLayersPendingRemoval.clear();
2898 }
2899
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002900 // If this transaction is part of a window animation then the next frame
2901 // we composite should be considered an animation as well.
2902 mAnimCompositionPending = mAnimTransactionPending;
2903
Nataniel Borges2b796da2019-02-15 13:32:18 -08002904 withTracingLock([&]() {
2905 mDrawingState = mCurrentState;
2906 // clear the "changed" flags in current state
2907 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002908
chaviw74d90ad2019-04-26 14:45:26 -07002909 mDrawingState.traverseInZOrder([&](Layer* layer) {
2910 layer->commitChildList();
2911
2912 // If the layer can be reached when traversing mDrawingState, then the layer is no
2913 // longer offscreen. Remove the layer from the offscreenLayer set.
2914 if (mOffscreenLayers.count(layer)) {
2915 mOffscreenLayers.erase(layer);
2916 }
2917 });
2918
2919 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002921
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002922 mTransactionPending = false;
2923 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002924 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925}
2926
Nataniel Borges2b796da2019-02-15 13:32:18 -08002927void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2928 if (mTracingEnabledChanged) {
2929 mTracingEnabled = mTracing.isEnabled();
2930 mTracingEnabledChanged = false;
2931 }
2932
2933 // Synchronize with Tracing thread
2934 std::unique_lock<std::mutex> lock;
2935 if (mTracingEnabled) {
2936 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2937 }
2938
2939 lockedOperation();
2940
2941 // Synchronize with Tracing thread
2942 if (mTracingEnabled) {
2943 lock.unlock();
2944 }
2945}
2946
chaviw74d90ad2019-04-26 14:45:26 -07002947void SurfaceFlinger::commitOffscreenLayers() {
2948 for (Layer* offscreenLayer : mOffscreenLayers) {
2949 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2950 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2951 if (!trFlags) return;
2952
2953 layer->doTransaction(0);
2954 layer->commitChildList();
2955 });
2956 }
2957}
2958
Lloyd Pique32cbe282018-10-19 13:09:22 -07002959void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002960 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002961 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002963
Lloyd Pique32cbe282018-10-19 13:09:22 -07002964 auto display = displayDevice->getCompositionDisplay();
2965
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 Region aboveOpaqueLayers;
2967 Region aboveCoveredLayers;
2968 Region dirty;
2969
Mathias Agopian87baae12012-07-31 12:38:26 -07002970 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971
Robert Carr2047fae2016-11-28 14:09:09 -08002972 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002973 // start with the whole surface at its current location
2974 const Layer::State& s(layer->getDrawingState());
2975
Jesse Hall01e29052013-02-19 16:13:35 -08002976 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08002977 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002978 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002980
Mathias Agopianab028732010-03-16 16:41:46 -07002981 /*
2982 * opaqueRegion: area of a surface that is fully opaque.
2983 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002985
2986 /*
2987 * visibleRegion: area of a surface that is visible on screen
2988 * and not fully transparent. This is essentially the layer's
2989 * footprint minus the opaque regions above it.
2990 * Areas covered by a translucent surface are considered visible.
2991 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002993
2994 /*
2995 * coveredRegion: area of a surface that is covered by all
2996 * visible regions above it (which includes the translucent areas).
2997 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002999
Jesse Halla8026d22012-09-25 13:25:04 -07003000 /*
3001 * transparentRegion: area of a surface that is hinted to be completely
3002 * transparent. This is only used to tell when the layer has no visible
3003 * non-transparent regions and can be removed from the layer list. It
3004 * does not affect the visibleRegion of this layer or any layers
3005 * beneath it. The hint may not be correct if apps don't respect the
3006 * SurfaceView restrictions (which, sadly, some don't).
3007 */
3008 Region transparentRegion;
3009
Mathias Agopianab028732010-03-16 16:41:46 -07003010
3011 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003012 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003013 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003014 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003015
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003017 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003018 if (!visibleRegion.isEmpty()) {
3019 // Remove the transparent area from the visible region
3020 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003021 if (tr.preserveRects()) {
3022 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003023 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003025 // transformation too complex, can't do the
3026 // transparent region optimization.
3027 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 }
Mathias Agopianab028732010-03-16 16:41:46 -07003029 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030
Mathias Agopianab028732010-03-16 16:41:46 -07003031 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003032 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003033 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003034 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003035 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003036 // the opaque region is the layer's footprint
3037 opaqueRegion = visibleRegion;
3038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 }
3040 }
3041
Robert Carre5f4f692018-01-12 13:12:28 -08003042 if (visibleRegion.isEmpty()) {
3043 layer->clearVisibilityRegions();
3044 return;
3045 }
3046
Mathias Agopianab028732010-03-16 16:41:46 -07003047 // Clip the covered region to the visible region
3048 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3049
3050 // Update aboveCoveredLayers for next (lower) layer
3051 aboveCoveredLayers.orSelf(visibleRegion);
3052
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 // subtract the opaque region covered by the layers above us
3054 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055
3056 // compute this layer's dirty region
3057 if (layer->contentDirty) {
3058 // we need to invalidate the whole region
3059 dirty = visibleRegion;
3060 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003061 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062 layer->contentDirty = false;
3063 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003064 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003065 * the exposed region consists of two components:
3066 * 1) what's VISIBLE now and was COVERED before
3067 * 2) what's EXPOSED now less what was EXPOSED before
3068 *
3069 * note that (1) is conservative, we start with the whole
3070 * visible region but only keep what used to be covered by
3071 * something -- which mean it may have been exposed.
3072 *
3073 * (2) handles areas that were not covered by anything but got
3074 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003075 */
Mathias Agopianab028732010-03-16 16:41:46 -07003076 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 const Region oldVisibleRegion = layer->visibleRegion;
3078 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003079 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3080 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 }
3082 dirty.subtractSelf(aboveOpaqueLayers);
3083
3084 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003085 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086
Mathias Agopianab028732010-03-16 16:41:46 -07003087 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003089
Jesse Halla8026d22012-09-25 13:25:04 -07003090 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 layer->setVisibleRegion(visibleRegion);
3092 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003093 layer->setVisibleNonTransparentRegion(
3094 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003095 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096
Mathias Agopian87baae12012-07-31 12:38:26 -07003097 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098}
3099
Chia-I Wuab0c3192017-08-01 11:29:00 -07003100void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003101 for (const auto& [token, displayDevice] : mDisplays) {
3102 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003103 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003104 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003105 }
3106 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003107}
3108
Dan Stoza6b9454d2014-11-07 16:00:59 -08003109bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110{
Ady Abraham09bd3922019-04-08 10:44:56 -07003111 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003112 ALOGV("handlePageFlip");
3113
Brian Andersond6927fb2016-07-23 23:37:30 -07003114 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003117 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003118 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003119
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003120 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3121
Eric Penner51c59cd2014-07-28 19:51:58 -07003122 // Store the set of layers that need updates. This set must not change as
3123 // buffers are being latched, as this could result in a deadlock.
3124 // Example: Two producers share the same command stream and:
3125 // 1.) Layer 0 is latched
3126 // 2.) Layer 0 gets a new frame
3127 // 2.) Layer 1 gets a new frame
3128 // 3.) Layer 1 is latched.
3129 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3130 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003131 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003132 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003133 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003134 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003135 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003136 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003137 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003138 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003139 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003140 } else {
3141 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142 }
Robert Carr2047fae2016-11-28 14:09:09 -08003143 });
3144
chaviw49a108c2019-08-12 11:23:06 -07003145 // The client can continue submitting buffers for offscreen layers, but they will not
3146 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3147 // layers to ensure dequeueBuffer doesn't block indefinitely.
3148 for (Layer* offscreenLayer : mOffscreenLayers) {
3149 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
3150 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3151 }
3152
Lloyd Piquef2c79392018-12-20 16:23:33 -08003153 if (!mLayersWithQueuedFrames.empty()) {
3154 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3155 // writes to Layer current state. See also b/119481871
3156 Mutex::Autolock lock(mStateLock);
3157
3158 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003159 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003160 mLayersPendingRefresh.push_back(layer);
3161 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003162 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003163 if (layer->isBufferLatched()) {
3164 newDataLatched = true;
3165 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003166 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003167 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003168
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003169 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003170
3171 // If we will need to wake up at some time in the future to deal with a
3172 // queued frame that shouldn't be displayed during this vsync period, wake
3173 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003174 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003175 signalLayerUpdate();
3176 }
3177
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003178 // enter boot animation on first buffer latch
3179 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3180 ALOGI("Enter boot animation");
3181 mBootStage = BootStage::BOOTANIMATION;
3182 }
3183
Dan Stoza6b9454d2014-11-07 16:00:59 -08003184 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003185 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186}
3187
Mathias Agopianad456f92011-01-13 17:53:01 -08003188void SurfaceFlinger::invalidateHwcGeometry()
3189{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003190 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003191}
3192
Lloyd Pique32cbe282018-10-19 13:09:22 -07003193void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003194 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003195 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003196 // We only need to actually compose the display if:
3197 // 1) It is being handled by hardware composer, which may need this to
3198 // keep its virtual display state machine in sync, or
3199 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003200 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003202 return;
3203 }
3204
Dan Stoza9e56aa02015-11-02 13:00:03 -08003205 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003206 base::unique_fd readyFence;
Lloyd Pique688abd42019-02-15 15:42:24 -08003207 if (!display->composeSurfaces(Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003208
3209 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003210 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211}
3212
Robert Carrc0df3122019-04-11 13:18:21 -07003213status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3214 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3215 const sp<IBinder>& parentHandle,
3216 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003217 // add this layer to the current state list
3218 {
3219 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003220 sp<Layer> parent;
3221 if (parentHandle != nullptr) {
3222 parent = fromHandle(parentHandle);
3223 if (parent == nullptr) {
3224 return NAME_NOT_FOUND;
3225 }
3226 } else {
3227 parent = parentLayer;
3228 }
3229
Robert Carr1f0a16a2016-10-24 16:27:39 -07003230 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003231 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003232 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003233 return NO_MEMORY;
3234 }
Robert Carrc0df3122019-04-11 13:18:21 -07003235
3236 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3237
Robert Carrb89ea9d2018-12-10 13:01:14 -08003238 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003239 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003240 } else if (parent == nullptr) {
3241 lbc->onRemovedFromCurrentState();
3242 } else if (parent->isRemovedFromCurrentState()) {
3243 parent->addChild(lbc);
3244 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003245 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246 parent->addChild(lbc);
3247 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003248
Yiwei Zhang243b3782018-05-15 17:40:04 -07003249 if (gbc != nullptr) {
3250 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3251 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3252 mMaxGraphicBufferProducerListSize,
3253 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3254 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003255 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003256 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003258 }
3259
Mathias Agopian96f08192010-06-02 23:28:45 -07003260 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003261 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003262
Dan Stoza7d89d062015-04-30 13:29:25 -07003263 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003264}
3265
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003266uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003267 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003268}
3269
Mathias Agopian3f844832013-08-07 21:24:32 -07003270uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003271 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272}
3273
Mathias Agopian3f844832013-08-07 21:24:32 -07003274uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003275 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003276}
3277
3278uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003279 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003280 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003281 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003283 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284 }
3285 return old;
3286}
3287
Marissa Wall713b63f2018-10-17 15:42:43 -07003288bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003289 // to prevent onHandleDestroyed from being called while the lock is held,
3290 // we must keep a copy of the transactions (specifically the composer
3291 // states) around outside the scope of the lock
3292 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003293 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003294 {
3295 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003296
Valerie Haufce31b82019-04-30 16:41:14 -07003297 auto it = mTransactionQueues.begin();
3298 while (it != mTransactionQueues.end()) {
3299 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003300
Valerie Haufce31b82019-04-30 16:41:14 -07003301 while (!transactionQueue.empty()) {
3302 const auto& transaction = transactionQueue.front();
3303 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003304 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003305 transaction.states)) {
3306 setTransactionFlags(eTransactionFlushNeeded);
3307 break;
3308 }
3309 transactions.push_back(transaction);
3310 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3311 mPendingInputWindowCommands, transaction.desiredPresentTime,
3312 transaction.buffer, transaction.callback,
3313 transaction.postTime, transaction.privileged,
3314 /*isMainThread*/ true);
3315 transactionQueue.pop();
3316 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003317 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003318
Valerie Haufce31b82019-04-30 16:41:14 -07003319 if (transactionQueue.empty()) {
3320 it = mTransactionQueues.erase(it);
3321 mTransactionCV.broadcast();
3322 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003323 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003324 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003325 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003326 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003327 return flushedATransaction;
3328}
3329
3330bool SurfaceFlinger::transactionFlushNeeded() {
3331 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003332}
3333
chaviwca27f252018-02-06 16:46:39 -08003334
Marissa Wall17b4e452018-12-26 16:32:34 -08003335bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003336 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003337 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003338 if (!useCachedExpectedPresentTime)
3339 populateExpectedPresentTime();
3340
3341 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003342 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3343 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3344 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3345 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3346 return false;
3347 }
3348
Marissa Wall713b63f2018-10-17 15:42:43 -07003349 for (const ComposerState& state : states) {
3350 const layer_state_t& s = state.state;
3351 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3352 continue;
3353 }
3354 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003355 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003356 }
3357 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003358 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003359}
3360
3361void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3362 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003363 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003364 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003365 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003366 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003367 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003368 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003369
Valerie Haubc6ddb12019-03-08 11:10:15 -08003370 const int64_t postTime = systemTime();
3371
Robert Carr14167e02019-02-13 13:50:55 -08003372 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3373
Mathias Agopian698c0872011-06-28 19:09:31 -07003374 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003375
Marissa Wall713b63f2018-10-17 15:42:43 -07003376 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003377 auto itr = mTransactionQueues.find(applyToken);
3378 // if this is an animation frame, wait until prior animation frame has
3379 // been applied by SF
3380 if (flags & eAnimation) {
3381 while (itr != mTransactionQueues.end()) {
3382 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3383 if (CC_UNLIKELY(err != NO_ERROR)) {
3384 ALOGW_IF(err == TIMED_OUT,
3385 "setTransactionState timed out "
3386 "waiting for animation frame to apply");
3387 break;
3388 }
3389 itr = mTransactionQueues.find(applyToken);
3390 }
3391 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003392
3393 // Expected present time is computed and cached on invalidate, so it may be stale.
3394 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3395 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003396 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003397 uncacheBuffer, listenerCallbacks, postTime,
3398 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003399 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003400 return;
3401 }
3402
Valerie Haubc6ddb12019-03-08 11:10:15 -08003403 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003404 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003405}
3406
3407void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003408 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003409 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003410 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003411 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003412 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003413 const int64_t postTime, bool privileged,
3414 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003415 uint32_t transactionFlags = 0;
3416
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003417 if (flags & eAnimation) {
3418 // For window updates that are part of an animation we must wait for
3419 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003420 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003421 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 if (CC_UNLIKELY(err != NO_ERROR)) {
3423 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003424 // caller after a few seconds.
3425 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3426 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003427 mAnimTransactionPending = false;
3428 break;
3429 }
3430 }
3431 }
3432
chaviwca27f252018-02-06 16:46:39 -08003433 for (const DisplayState& display : displays) {
3434 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003435 }
3436
Marissa Walld600d572019-03-26 15:38:50 -07003437 // In case the client has sent a Transaction that should receive callbacks but without any
3438 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3439 // to the callback thread so it can send an empty callback
3440 if (!listenerCallbacks.empty()) {
3441 mTransactionCompletedThread.run();
3442 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003443 for (const auto& listenerCallback : listenerCallbacks) {
3444 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003445 }
3446
Marissa Walle2ffb422018-10-12 11:33:52 -07003447 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003448 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003449 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3450 postTime, privileged);
3451 }
3452
Marissa Wallefb71af2019-06-27 14:45:53 -07003453 for (const auto& listenerCallback : listenerCallbacks) {
3454 mTransactionCompletedThread.endRegistration(listenerCallback);
3455 }
3456
Marissa Walle2ffb422018-10-12 11:33:52 -07003457 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003458 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003459 mTransactionCompletedThread.sendCallbacks();
3460 }
3461 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003462
chaviw273171b2018-12-26 11:46:30 -08003463 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3464
Marissa Wall947d34e2019-03-29 14:03:53 -07003465 if (uncacheBuffer.isValid()) {
3466 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003467 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003468 }
3469
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003470 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3471 // anyway. This can be used as a flush mechanism for previous async transactions.
3472 // Empty animation transaction can be used to simulate back-pressure, so also force a
3473 // transaction for empty animation transactions.
3474 if (transactionFlags == 0 &&
3475 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003476 transactionFlags = eTransactionNeeded;
3477 }
3478
Marissa Wall06255332019-03-27 13:48:27 -07003479 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3480 // so we don't have to wake up again next frame to preform an uneeded traversal.
3481 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3482 transactionFlags = transactionFlags & (~eTraversalNeeded);
3483 mTraversalNeededMainThread = true;
3484 }
3485
Mathias Agopian386aa982011-11-07 21:58:03 -08003486 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003487 if (mInterceptor->isEnabled()) {
3488 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003489 }
Irvel468051e2016-06-13 16:44:44 -07003490
Mathias Agopian386aa982011-11-07 21:58:03 -08003491 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003492 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3493 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003494 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003495
3496 // if this is a synchronous transaction, wait for it to take effect
3497 // before returning.
3498 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003499 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003500 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003501 if (flags & eAnimation) {
3502 mAnimTransactionPending = true;
3503 }
chaviw4fe36852019-04-15 16:25:49 -07003504 if (mPendingInputWindowCommands.syncInputWindows) {
3505 mPendingSyncInputWindows = true;
3506 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003507
3508 // applyTransactionState can be called by either the main SF thread or by
3509 // another process through setTransactionState. While a given process may wish
3510 // to wait on synchronous transactions, the main SF thread should never
3511 // be blocked. Therefore, we only wait if isMainThread is false.
3512 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003513 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3514 if (CC_UNLIKELY(err != NO_ERROR)) {
3515 // just in case something goes wrong in SF, return to the
3516 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003517 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3518 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003519 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003520 break;
3521 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003522 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 }
3524}
3525
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003526uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3527 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3528 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003529
Mathias Agopiane57f2922012-08-09 16:29:12 -07003530 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003531 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3532
3533 const uint32_t what = s.what;
3534 if (what & DisplayState::eSurfaceChanged) {
3535 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3536 state.surface = s.surface;
3537 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003538 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003539 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003540 if (what & DisplayState::eLayerStackChanged) {
3541 if (state.layerStack != s.layerStack) {
3542 state.layerStack = s.layerStack;
3543 flags |= eDisplayTransactionNeeded;
3544 }
3545 }
3546 if (what & DisplayState::eDisplayProjectionChanged) {
3547 if (state.orientation != s.orientation) {
3548 state.orientation = s.orientation;
3549 flags |= eDisplayTransactionNeeded;
3550 }
3551 if (state.frame != s.frame) {
3552 state.frame = s.frame;
3553 flags |= eDisplayTransactionNeeded;
3554 }
3555 if (state.viewport != s.viewport) {
3556 state.viewport = s.viewport;
3557 flags |= eDisplayTransactionNeeded;
3558 }
3559 }
3560 if (what & DisplayState::eDisplaySizeChanged) {
3561 if (state.width != s.width) {
3562 state.width = s.width;
3563 flags |= eDisplayTransactionNeeded;
3564 }
3565 if (state.height != s.height) {
3566 state.height = s.height;
3567 flags |= eDisplayTransactionNeeded;
3568 }
3569 }
3570
Mathias Agopiane57f2922012-08-09 16:29:12 -07003571 return flags;
3572}
3573
Robert Carr14167e02019-02-13 13:50:55 -08003574bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003575 IPCThreadState* ipc = IPCThreadState::self();
3576 const int pid = ipc->getCallingPid();
3577 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003578 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003579 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003580 return false;
3581 }
3582 return true;
3583}
3584
Marissa Wall3dad52d2019-03-22 14:03:19 -07003585uint32_t SurfaceFlinger::setClientStateLocked(
3586 const ComposerState& composerState, int64_t desiredPresentTime,
3587 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3588 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003589 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003590
Vishnu Nairf03652d2019-07-16 17:56:56 -07003591 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003592 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003593 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003594 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003595 new CallbackHandle(listenerCallback.transactionCompletedListener,
3596 listenerCallback.callbackIds, s.surface));
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 return 0;
3599 }
3600
chaviw8b3871a2017-11-01 17:41:01 -07003601 uint32_t flags = 0;
3602
Garfield Tan8a3083e2018-12-03 13:21:07 -08003603 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003604 bool geometryAppliesWithResize =
3605 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003606
3607 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3608 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003609 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003610 layer->pushPendingState();
3611 }
3612
chaviw8b3871a2017-11-01 17:41:01 -07003613 if (what & layer_state_t::ePositionChanged) {
3614 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3615 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003616 }
chaviw8b3871a2017-11-01 17:41:01 -07003617 }
3618 if (what & layer_state_t::eLayerChanged) {
3619 // NOTE: index needs to be calculated before we update the state
3620 const auto& p = layer->getParent();
3621 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003622 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003623 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003624 mCurrentState.layersSortedByZ.removeAt(idx);
3625 mCurrentState.layersSortedByZ.add(layer);
3626 // we need traversal (state changed)
3627 // AND transaction (list changed)
3628 flags |= eTransactionNeeded|eTraversalNeeded;
3629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 } else {
3631 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003632 flags |= eTransactionNeeded|eTraversalNeeded;
3633 }
3634 }
chaviw8b3871a2017-11-01 17:41:01 -07003635 }
3636 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003637 // NOTE: index needs to be calculated before we update the state
3638 const auto& p = layer->getParent();
3639 if (p == nullptr) {
3640 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3641 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3642 mCurrentState.layersSortedByZ.removeAt(idx);
3643 mCurrentState.layersSortedByZ.add(layer);
3644 // we need traversal (state changed)
3645 // AND transaction (list changed)
3646 flags |= eTransactionNeeded|eTraversalNeeded;
3647 }
3648 } else {
3649 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3650 flags |= eTransactionNeeded|eTraversalNeeded;
3651 }
chaviw8b3871a2017-11-01 17:41:01 -07003652 }
3653 }
3654 if (what & layer_state_t::eSizeChanged) {
3655 if (layer->setSize(s.w, s.h)) {
3656 flags |= eTraversalNeeded;
3657 }
3658 }
3659 if (what & layer_state_t::eAlphaChanged) {
3660 if (layer->setAlpha(s.alpha))
3661 flags |= eTraversalNeeded;
3662 }
3663 if (what & layer_state_t::eColorChanged) {
3664 if (layer->setColor(s.color))
3665 flags |= eTraversalNeeded;
3666 }
Peiyong Lind3788632018-09-18 16:01:31 -07003667 if (what & layer_state_t::eColorTransformChanged) {
3668 if (layer->setColorTransform(s.colorTransform)) {
3669 flags |= eTraversalNeeded;
3670 }
3671 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003672 if (what & layer_state_t::eBackgroundColorChanged) {
3673 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3674 flags |= eTraversalNeeded;
3675 }
3676 }
chaviw8b3871a2017-11-01 17:41:01 -07003677 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003678 // TODO: b/109894387
3679 //
3680 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3681 // rotation. To see the problem observe that if we have a square parent, and a child
3682 // of the same size, then we rotate the child 45 degrees around it's center, the child
3683 // must now be cropped to a non rectangular 8 sided region.
3684 //
3685 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3686 // private API, and the WindowManager only uses rotation in one case, which is on a top
3687 // level layer in which cropping is not an issue.
3688 //
3689 // However given that abuse of rotation matrices could lead to surfaces extending outside
3690 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3691 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3692 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003693 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003694 flags |= eTraversalNeeded;
3695 }
3696 if (what & layer_state_t::eTransparentRegionChanged) {
3697 if (layer->setTransparentRegionHint(s.transparentRegion))
3698 flags |= eTraversalNeeded;
3699 }
3700 if (what & layer_state_t::eFlagsChanged) {
3701 if (layer->setFlags(s.flags, s.mask))
3702 flags |= eTraversalNeeded;
3703 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003704 if (what & layer_state_t::eCropChanged_legacy) {
3705 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003706 flags |= eTraversalNeeded;
3707 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003708 if (what & layer_state_t::eCornerRadiusChanged) {
3709 if (layer->setCornerRadius(s.cornerRadius))
3710 flags |= eTraversalNeeded;
3711 }
chaviw8b3871a2017-11-01 17:41:01 -07003712 if (what & layer_state_t::eLayerStackChanged) {
3713 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3714 // We only allow setting layer stacks for top level layers,
3715 // everything else inherits layer stack from its parent.
3716 if (layer->hasParent()) {
3717 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3718 layer->getName().string());
3719 } else if (idx < 0) {
3720 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3721 "that also does not appear in the top level layer list. Something"
3722 " has gone wrong.", layer->getName().string());
3723 } else if (layer->setLayerStack(s.layerStack)) {
3724 mCurrentState.layersSortedByZ.removeAt(idx);
3725 mCurrentState.layersSortedByZ.add(layer);
3726 // we need traversal (state changed)
3727 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003728 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003729 }
3730 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003731 if (what & layer_state_t::eDeferTransaction_legacy) {
3732 if (s.barrierHandle_legacy != nullptr) {
3733 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3734 } else if (s.barrierGbp_legacy != nullptr) {
3735 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003736 if (authenticateSurfaceTextureLocked(gbp)) {
3737 const auto& otherLayer =
3738 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003739 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003740 } else {
3741 ALOGE("Attempt to defer transaction to to an"
3742 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003743 }
3744 }
chaviw8b3871a2017-11-01 17:41:01 -07003745 // We don't trigger a traversal here because if no other state is
3746 // changed, we don't want this to cause any more work
3747 }
chaviw8b3871a2017-11-01 17:41:01 -07003748 if (what & layer_state_t::eReparentChildren) {
3749 if (layer->reparentChildren(s.reparentHandle)) {
3750 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003751 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003752 }
chaviw8b3871a2017-11-01 17:41:01 -07003753 if (what & layer_state_t::eDetachChildren) {
3754 layer->detachChildren();
3755 }
3756 if (what & layer_state_t::eOverrideScalingModeChanged) {
3757 layer->setOverrideScalingMode(s.overrideScalingMode);
3758 // We don't trigger a traversal here because if no other state is
3759 // changed, we don't want this to cause any more work
3760 }
Marissa Wall61c58622018-07-18 10:12:20 -07003761 if (what & layer_state_t::eTransformChanged) {
3762 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3763 }
3764 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3765 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3766 flags |= eTraversalNeeded;
3767 }
3768 if (what & layer_state_t::eCropChanged) {
3769 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3770 }
Marissa Wall861616d2018-10-22 12:52:23 -07003771 if (what & layer_state_t::eFrameChanged) {
3772 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3773 }
Marissa Wall61c58622018-07-18 10:12:20 -07003774 if (what & layer_state_t::eAcquireFenceChanged) {
3775 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3776 }
3777 if (what & layer_state_t::eDataspaceChanged) {
3778 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3779 }
3780 if (what & layer_state_t::eHdrMetadataChanged) {
3781 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3782 }
3783 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3784 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3785 }
3786 if (what & layer_state_t::eApiChanged) {
3787 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3788 }
3789 if (what & layer_state_t::eSidebandStreamChanged) {
3790 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3791 }
Robert Carr720e5062018-07-30 17:45:14 -07003792 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003793 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003794 layer->setInputInfo(s.inputInfo);
3795 flags |= eTraversalNeeded;
3796 } else {
3797 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3798 }
Robert Carr720e5062018-07-30 17:45:14 -07003799 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003800 if (what & layer_state_t::eMetadataChanged) {
3801 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3802 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003803 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3804 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3805 flags |= eTraversalNeeded;
3806 }
3807 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003808 // This has to happen after we reparent children because when we reparent to null we remove
3809 // child layers from current state and remove its relative z. If the children are reparented in
3810 // the same transaction, then we have to make sure we reparent the children first so we do not
3811 // lose its relative z order.
3812 if (what & layer_state_t::eReparent) {
3813 bool hadParent = layer->hasParent();
3814 if (layer->reparent(s.parentHandleForChild)) {
3815 if (!hadParent) {
3816 mCurrentState.layersSortedByZ.remove(layer);
3817 }
3818 flags |= eTransactionNeeded | eTraversalNeeded;
3819 }
3820 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07003822 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003823 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003824 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3825 }
3826 }
Marissa Wall78b72202019-03-15 14:58:34 -07003827 bool bufferChanged = what & layer_state_t::eBufferChanged;
3828 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3829 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003830 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003831 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003832 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3833 if (success) {
3834 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3835 success = ClientCache::getInstance()
3836 .registerErasedRecipient(s.cachedBuffer,
3837 wp<ClientCache::ErasedRecipient>(this));
3838 if (!success) {
3839 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3840 }
3841 }
Marissa Wall78b72202019-03-15 14:58:34 -07003842 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003843 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003844 } else if (bufferChanged) {
3845 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003846 }
Marissa Wall78b72202019-03-15 14:58:34 -07003847 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003848 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003849 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003850 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003851 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003852 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3853 // Do not put anything that updates layer state or modifies flags after
3854 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003855 return flags;
3856}
3857
chaviw273171b2018-12-26 11:46:30 -08003858uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3859 uint32_t flags = 0;
3860 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3861 flags |= eTraversalNeeded;
3862 }
3863
chaviwa911b102019-02-14 10:18:33 -08003864 if (inputWindowCommands.syncInputWindows) {
3865 flags |= eTraversalNeeded;
3866 }
3867
Vishnu Nairec0ab382019-02-13 15:32:56 -08003868 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003869 return flags;
3870}
3871
Marissa Wall2d814fb2019-04-09 18:52:57 +00003872status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3873 uint32_t h, PixelFormat format, uint32_t flags,
3874 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003875 sp<IGraphicBufferProducer>* gbp,
3876 const sp<IBinder>& parentHandle,
3877 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003878 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003879 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003880 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003882 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003883
Robert Carrc0df3122019-04-11 13:18:21 -07003884 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3885 "Expected only one of parentLayer or parentHandle to be non-null. "
3886 "Programmer error?");
3887
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 status_t result = NO_ERROR;
3889
3890 sp<Layer> layer;
3891
Cody Northropbc755282017-03-31 12:00:08 -06003892 String8 uniqueName = getUniqueLayerName(name);
3893
Evan Roskya1f1e152019-01-24 16:17:46 -08003894 bool primaryDisplayOnly = false;
3895
3896 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3897 // TODO b/64227542
3898 if (metadata.has(METADATA_WINDOW_TYPE)) {
3899 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3900 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003901 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003902 primaryDisplayOnly = true;
3903 }
3904 }
3905
Mathias Agopian3165cc22012-08-08 19:42:09 -07003906 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003907 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003908 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3909 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003910
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003912 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003913 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3914 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003915 break;
chaviw13fdc492017-06-27 12:40:18 -07003916 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003917 // check if buffer size is set for color layer.
3918 if (w > 0 || h > 0) {
3919 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3920 int(w), int(h));
3921 return BAD_VALUE;
3922 }
3923
Evan Roskya1f1e152019-01-24 16:17:46 -08003924 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3925 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003926 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003927 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003928 // check if buffer size is set for container layer.
3929 if (w > 0 || h > 0) {
3930 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3931 int(w), int(h));
3932 return BAD_VALUE;
3933 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003934 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3935 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003936 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003937 default:
3938 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003939 break;
3940 }
3941
Dan Stoza7d89d062015-04-30 13:29:25 -07003942 if (result != NO_ERROR) {
3943 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003945
Evan Roskya1f1e152019-01-24 16:17:46 -08003946 if (primaryDisplayOnly) {
3947 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003948 }
3949
Robert Carrb89ea9d2018-12-10 13:01:14 -08003950 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003951 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3952 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003953 if (result != NO_ERROR) {
3954 return result;
3955 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003956 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003957
3958 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003959 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003960}
3961
Cody Northropbc755282017-03-31 12:00:08 -06003962String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3963{
3964 bool matchFound = true;
3965 uint32_t dupeCounter = 0;
3966
3967 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3968 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3969
Dan Stoza436ccf32018-06-21 12:10:12 -07003970 // Grab the state lock since we're accessing mCurrentState
3971 Mutex::Autolock lock(mStateLock);
3972
Cody Northropbc755282017-03-31 12:00:08 -06003973 // Loop over layers until we're sure there is no matching name
3974 while (matchFound) {
3975 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003976 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003977 if (layer->getName() == uniqueName) {
3978 matchFound = true;
3979 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3980 }
3981 });
3982 }
3983
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003984 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3985 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003986
3987 return uniqueName;
3988}
3989
Marissa Wallfd668622018-05-10 10:21:13 -07003990status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3991 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003992 LayerMetadata metadata, PixelFormat& format,
3993 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003994 sp<IGraphicBufferProducer>* gbp,
3995 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003997 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 case PIXEL_FORMAT_TRANSPARENT:
3999 case PIXEL_FORMAT_TRANSLUCENT:
4000 format = PIXEL_FORMAT_RGBA_8888;
4001 break;
4002 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004003 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 break;
4005 }
4006
Evan Roskya1f1e152019-01-24 16:17:46 -08004007 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4008 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004009 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004010 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004011 *handle = layer->getHandle();
4012 *gbp = layer->getProducer();
4013 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004015
Marissa Wallfd668622018-05-10 10:21:13 -07004016 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018}
4019
Marissa Wall61c58622018-07-18 10:12:20 -07004020status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4021 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004022 LayerMetadata metadata, sp<IBinder>* handle,
4023 sp<Layer>* outLayer) {
4024 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4025 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004026 *handle = layer->getHandle();
4027 *outLayer = layer;
4028
4029 return NO_ERROR;
4030}
4031
Evan Roskya1f1e152019-01-24 16:17:46 -08004032status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4033 uint32_t h, uint32_t flags, LayerMetadata metadata,
4034 sp<IBinder>* handle, sp<Layer>* outLayer) {
4035 *outLayer = getFactory().createColorLayer(
4036 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004037 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004039}
4040
Evan Roskya1f1e152019-01-24 16:17:46 -08004041status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4042 uint32_t w, uint32_t h, uint32_t flags,
4043 LayerMetadata metadata, sp<IBinder>* handle,
4044 sp<Layer>* outLayer) {
4045 *outLayer = getFactory().createContainerLayer(
4046 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004047 *handle = (*outLayer)->getHandle();
4048 return NO_ERROR;
4049}
4050
4051
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004052void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004053 mLayersPendingRemoval.add(layer);
4054 mLayersRemoved = true;
4055 setTransactionFlags(eTransactionNeeded);
4056}
4057
Robert Carr695d5282018-12-18 15:27:58 -08004058void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004059{
Robert Carr2e102c92018-10-23 12:11:15 -07004060 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004061 // If a layer has a parent, we allow it to out-live it's handle
4062 // with the idea that the parent holds a reference and will eventually
4063 // be cleaned up. However no one cleans up the top-level so we do so
4064 // here.
4065 if (layer->getParent() == nullptr) {
4066 mCurrentState.layersSortedByZ.remove(layer);
4067 }
4068 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004069
4070 auto it = mLayersByLocalBinderToken.begin();
4071 while (it != mLayersByLocalBinderToken.end()) {
4072 if (it->second == layer) {
4073 it = mLayersByLocalBinderToken.erase(it);
4074 } else {
4075 it++;
4076 }
4077 }
4078
Robert Carr695d5282018-12-18 15:27:58 -08004079 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004080}
4081
Mathias Agopianb60314a2012-04-10 22:09:54 -07004082// ---------------------------------------------------------------------------
4083
Andy McFadden13a082e2012-08-24 10:16:42 -07004084void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004085 const auto display = getDefaultDisplayDeviceLocked();
4086 if (!display) return;
4087
4088 const sp<IBinder> token = display->getDisplayToken().promote();
4089 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004090
Jesse Hall01e29052013-02-19 16:13:35 -08004091 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004092 Vector<ComposerState> state;
4093 Vector<DisplayState> displays;
4094 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004095 d.what = DisplayState::eDisplayProjectionChanged |
4096 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004097 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004098 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004099 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004100 d.frame.makeInvalid();
4101 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004102 d.width = 0;
4103 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004104 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004105 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004106
Dominik Laskowskie9774092018-12-11 10:04:24 -08004107 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004108
Dominik Laskowski83b88212018-12-11 13:34:06 -08004109 const nsecs_t vsyncPeriod = getVsyncPeriod();
4110 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004111
Brian Andersond0010582017-03-07 13:20:31 -08004112 // Use phase of 0 since phase is not known.
4113 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004114 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004115 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004116}
4117
4118void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004119 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004120 postMessageAsync(
4121 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004122}
4123
Ady Abraham27c70212019-06-11 10:52:26 -07004124void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4125 if (mHWCVsyncState != enabled) {
4126 getHwComposer().setVsyncEnabled(displayId, enabled);
4127 mHWCVsyncState = enabled;
4128 }
4129}
4130
Dominik Laskowskie9774092018-12-11 10:04:24 -08004131void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004132 if (display->isVirtual()) {
4133 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004134 return;
4135 }
4136
Dominik Laskowski075d3172018-05-24 15:50:06 -07004137 const auto displayId = display->getId();
4138 LOG_ALWAYS_FATAL_IF(!displayId);
4139
Dominik Laskowski34157762018-10-31 13:07:19 -07004140 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004141
4142 int currentMode = display->getPowerMode();
4143 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004144 return;
4145 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147 display->setPowerMode(mode);
4148
Lloyd Pique4dccc412018-01-22 17:21:36 -08004149 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004150 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004151 }
4152
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004153 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004154 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004156 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004157 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004158 mScheduler->onScreenAcquired(mAppConnectionHandle);
4159 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004162 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004163 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004164 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004165
4166 struct sched_param param = {0};
4167 param.sched_priority = 1;
4168 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4169 ALOGW("Couldn't set SCHED_FIFO on display on");
4170 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004171 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004172 // Turn off the display
4173 struct sched_param param = {0};
4174 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4175 ALOGW("Couldn't set SCHED_OTHER on display off");
4176 }
4177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004179 mScheduler->disableHardwareVsync(true);
4180 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004181 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004182
Ady Abraham27c70212019-06-11 10:52:26 -07004183 // Make sure HWVsync is disabled before turning off the display
4184 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4185
Dominik Laskowski075d3172018-05-24 15:50:06 -07004186 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004187 mVisibleRegionsDirty = true;
4188 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004189 } else if (mode == HWC_POWER_MODE_DOZE ||
4190 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004191 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004192 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004193 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004194 mScheduler->onScreenAcquired(mAppConnectionHandle);
4195 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004196 }
4197 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4198 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004199 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004200 mScheduler->disableHardwareVsync(true);
4201 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004202 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004203 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004204 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004205 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004206 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004209 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004210 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004211 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004212 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004213 }
4214
Dominik Laskowski34157762018-10-31 13:07:19 -07004215 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216}
4217
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004218void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 const auto display = getDisplayDevice(displayToken);
4221 if (!display) {
4222 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4223 displayToken.get());
4224 } else if (display->isVirtual()) {
4225 ALOGW("Attempt to set power mode %d for virtual display", mode);
4226 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004227 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004229 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004230}
4231
4232// ---------------------------------------------------------------------------
4233
Dominik Laskowskic2867142019-01-21 11:33:38 -08004234status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4235 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004237
Mathias Agopianbd115332013-04-18 16:41:04 -07004238 IPCThreadState* ipc = IPCThreadState::self();
4239 const int pid = ipc->getCallingPid();
4240 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004241
Mathias Agopianbd115332013-04-18 16:41:04 -07004242 if ((uid != AID_SHELL) &&
4243 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004244 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4245 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004247 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004248 // (this would indicate SF is stuck, but we want to be able to
4249 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004250 status_t err = mStateLock.timedLock(s2ns(1));
4251 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004252 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result,
4254 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4255 "(no locks held)\n",
4256 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004257 }
4258
Dominik Laskowskic2867142019-01-21 11:33:38 -08004259 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004260
Dominik Laskowskic2867142019-01-21 11:33:38 -08004261 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004262 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004263 {"--dispsync"s,
4264 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004265 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4266 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4267 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4268 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4269 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4270 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004271 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004272 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4273 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004274
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004276
Dominik Laskowski46470112019-08-02 13:13:11 -07004277 const auto it = dumpers.find(flag);
4278 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004279 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004280 } else if (!asProto) {
4281 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004282 }
4283
Mathias Agopian9795c422009-08-26 16:36:26 -07004284 if (locked) {
4285 mStateLock.unlock();
4286 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004287
Dominik Laskowski46470112019-08-02 13:13:11 -07004288 if (it == dumpers.end()) {
4289 const LayersProto layersProto = dumpProtoFromMainThread();
4290 if (asProto) {
4291 result.append(layersProto.SerializeAsString());
4292 } else {
4293 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4294 result.append(LayerProtoParser::layerTreeToString(layerTree));
4295 result.append("\n");
4296 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004300 return NO_ERROR;
4301}
4302
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004303status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4304 if (asProto && mTracing.isEnabled()) {
4305 mTracing.writeToFileAsync();
4306 }
4307
4308 return doDump(fd, DumpArgs(), asProto);
4309}
4310
Dominik Laskowskic2867142019-01-21 11:33:38 -08004311void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312 mCurrentState.traverseInZOrder(
4313 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004314}
4315
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004317 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004318
Dominik Laskowskic2867142019-01-21 11:33:38 -08004319 if (args.size() > 1) {
4320 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004321 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004322 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004323 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004324 }
Robert Carr2047fae2016-11-28 14:09:09 -08004325 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326 } else {
4327 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 }
4329}
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004332 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004333 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004334 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004335 }
Robert Carr2047fae2016-11-28 14:09:09 -08004336 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004337
Svetoslavd85084b2014-03-20 10:28:31 -07004338 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004339}
4340
Dominik Laskowskic2867142019-01-21 11:33:38 -08004341void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4342 mTimeStats->parseArgs(asProto, args, result);
4343}
4344
Jamie Gennis6547ff42013-07-16 20:12:42 -07004345// This should only be called from the main thread. Otherwise it would need
4346// the lock and should use mCurrentState rather than mDrawingState.
4347void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004348 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004349 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004350 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004351
4352 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4353}
4354
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004356 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004357
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004358 if (isLayerTripleBufferingDisabled())
4359 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004360
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4362 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4363 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4364 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4365 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4366 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004367 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004368}
4369
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004370void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004371 mScheduler->dump(result);
4372 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
4373
4374 mRefreshRateStats.dump(result);
4375 result.append("\n");
4376
Ana Krulec757f63a2019-01-25 10:46:18 -08004377 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004378 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004379 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004380 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004381
Ady Abraham42b3beb2019-07-09 18:09:52 -07004382 StringAppendF(&result, "Allowed Display Configs: ");
Dominik Laskowski98041832019-08-01 18:35:59 -07004383 for (const auto& [type, rate] : mRefreshRateConfigs.getRefreshRates()) {
4384 if (rate && isDisplayConfigAllowed(rate->configId)) {
4385 StringAppendF(&result, "%" PRIu32 " Hz, ", rate->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004386 }
4387 }
4388 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4389 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004390
Ana Krulecc2870422019-01-29 19:00:58 -08004391 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004392}
4393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4395 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004396 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4397 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004398 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004399 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004400 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004401 }
David Sodman4a36e932017-11-07 14:29:47 -08004402 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004403 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004404 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4406 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004407}
4408
Dan Stozae77c7662016-05-13 11:37:28 -07004409void SurfaceFlinger::recordBufferingStats(const char* layerName,
4410 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004411 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4412 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004413 for (const auto& segment : history) {
4414 if (!segment.usedThirdBuffer) {
4415 stats.twoBufferTime += segment.totalTime;
4416 }
4417 if (segment.occupancyAverage < 1.0f) {
4418 stats.doubleBufferedTime += segment.totalTime;
4419 } else if (segment.occupancyAverage < 2.0f) {
4420 stats.tripleBufferedTime += segment.totalTime;
4421 }
4422 ++stats.numSegments;
4423 stats.totalTime += segment.totalTime;
4424 }
4425}
4426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4428 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004429
4430 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4431 const size_t count = currentLayers.size();
4432 for (size_t i=0 ; i<count ; i++) {
4433 currentLayers[i]->dumpFrameEvents(result);
4434 }
4435}
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004438 result.append("Buffering stats:\n");
4439 result.append(" [Layer name] <Active time> <Two buffer> "
4440 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004441 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004442 typedef std::tuple<std::string, float, float, float> BufferTuple;
4443 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004444 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004445 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004446 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004447 if (stats.numSegments == 0) {
4448 continue;
4449 }
4450 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4451 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4452 stats.totalTime;
4453 float doubleBufferRatio = static_cast<float>(
4454 stats.doubleBufferedTime) / stats.totalTime;
4455 float tripleBufferRatio = static_cast<float>(
4456 stats.tripleBufferedTime) / stats.totalTime;
4457 sorted.insert({activeTime, {name, twoBufferRatio,
4458 doubleBufferRatio, tripleBufferRatio}});
4459 }
4460 for (const auto& sortedPair : sorted) {
4461 float activeTime = sortedPair.first;
4462 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4464 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004465 }
4466 result.append("\n");
4467}
4468
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004470 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004471 const auto displayId = display->getId();
4472 if (!displayId) {
4473 continue;
4474 }
4475 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004476 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004477 continue;
4478 }
4479
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480 StringAppendF(&result,
4481 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4482 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 uint8_t port;
4484 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004485 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004486 result.append("no identification data\n");
4487 continue;
4488 }
4489
4490 if (!isEdid(data)) {
4491 result.append("unknown identification data: ");
4492 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004494 }
4495 result.append("\n");
4496 continue;
4497 }
4498
4499 const auto edid = parseEdid(data);
4500 if (!edid) {
4501 result.append("invalid EDID: ");
4502 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004504 }
4505 result.append("\n");
4506 continue;
4507 }
4508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004510 result.append(edid->displayName.data(), edid->displayName.length());
4511 result.append("\"\n");
4512 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004513}
4514
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004516 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4518 StringAppendF(&result, "DisplayColorSetting: %s\n",
4519 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004520
4521 // TODO: print out if wide-color mode is active or not
4522
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004523 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004524 const auto displayId = display->getId();
4525 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004526 continue;
4527 }
4528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004530 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004531 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004533 }
4534
Lloyd Pique32cbe282018-10-19 13:09:22 -07004535 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " Current color mode: %s (%d)\n",
4537 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004538 }
4539 result.append("\n");
4540}
4541
Vishnu Nair8406fd72019-07-30 11:29:31 -07004542LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004543 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004544 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004545 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004546 layer->writeToProtoDrawingState(layerProto, traceFlags);
4547 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004548 });
4549
4550 return layersProto;
4551}
4552
Vishnu Nair8406fd72019-07-30 11:29:31 -07004553LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4554 LayersProto layersProto;
4555 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4556 return layersProto;
4557}
4558
Dominik Laskowskic2867142019-01-21 11:33:38 -08004559void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4560 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004561 Colorizer colorizer(colorize);
4562
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 // figure out if we're stuck somewhere
4564 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4567
4568 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004569 * Dump library configuration.
4570 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571
4572 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004573 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004574 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004575 appendSfConfigString(result);
4576 appendUiConfigString(result);
4577 appendGuiConfigString(result);
4578 result.append("\n");
4579
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 result.append("\nDisplay identification data:\n");
4581 dumpDisplayIdentificationData(result);
4582
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004583 result.append("\nWide-Color information:\n");
4584 dumpWideColorInfo(result);
4585
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004586 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004587 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004588 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004589 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004590 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004591
Andy McFadden41d67d72014-04-25 16:58:34 -07004592 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004593 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004594 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004595 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004596 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004597
Dan Stozab90cf072015-03-05 11:05:59 -08004598 dumpStaticScreenStats(result);
4599 result.append("\n");
4600
Alec Mouri40189b02019-03-05 15:07:54 -08004601 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4602 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4603 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004604
Dan Stozae77c7662016-05-13 11:37:28 -07004605 dumpBufferingStats(result);
4606
Andy McFadden4803b742012-09-24 19:07:20 -07004607 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004608 * Dump the visible layer list
4609 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004610 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004611 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4613 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004615
Chia-I Wu2f884132018-09-13 15:17:58 -07004616 {
Lloyd Pique207def92019-02-28 16:09:52 -08004617 StringAppendF(&result, "Composition layers\n");
4618 mDrawingState.traverseInZOrder([&](Layer* layer) {
4619 auto compositionLayer = layer->getCompositionLayer();
4620 if (compositionLayer) compositionLayer->dump(result);
4621 });
4622 }
4623
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004624 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004625 * Dump Display state
4626 */
4627
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004628 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004630 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004631 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004632 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004633 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004634 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004635
4636 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004637 * Dump SurfaceFlinger global state
4638 */
4639
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004640 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004641 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004642 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004644 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004645
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004646 DebugEGLImageTracker::getInstance()->dump(result);
4647
Dominik Laskowski075d3172018-05-24 15:50:06 -07004648 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004649 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4650 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4652 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004653 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 StringAppendF(&result,
4655 " transaction-flags : %08x\n"
4656 " gpu_to_cpu_unsupported : %d\n",
4657 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004658
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004659 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004660 displayId && getHwComposer().isConnected(*displayId)) {
4661 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result,
4663 " refresh-rate : %f fps\n"
4664 " x-dpi : %f\n"
4665 " y-dpi : %f\n",
4666 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4667 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004668 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671
Dan Stozae22aec72016-08-01 13:20:59 -07004672 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004673 * Tracing state
4674 */
4675 mTracing.dump(result);
4676 result.append("\n");
4677
4678 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004679 * HWC layer minidump
4680 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004681 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004682 const auto displayId = display->getId();
4683 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004684 continue;
4685 }
4686
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004688 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004689 const sp<DisplayDevice> displayDevice = display;
4690 mCurrentState.traverseInZOrder(
4691 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004692 result.append("\n");
4693 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694
4695 /*
4696 * Dump HWComposer state
4697 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004699 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004701 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004703 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004704
4705 /*
4706 * Dump gralloc state
4707 */
4708 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4709 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004710
4711 /*
4712 * Dump VrFlinger state if in use.
4713 */
4714 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4715 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004716 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004717 result.append("\n");
4718 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004719
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004720 result.append(mTimeStats->miniDump());
4721 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722}
4723
Chia-I Wu28f320b2018-05-03 11:02:56 -07004724void SurfaceFlinger::updateColorMatrixLocked() {
4725 mat4 colorMatrix;
4726 if (mGlobalSaturationFactor != 1.0f) {
4727 // Rec.709 luma coefficients
4728 float3 luminance{0.213f, 0.715f, 0.072f};
4729 luminance *= 1.0f - mGlobalSaturationFactor;
4730 mat4 saturationMatrix = mat4(
4731 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4732 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4733 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4734 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4735 );
4736 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4737 } else {
4738 colorMatrix = mClientColorMatrix * mDaltonizer();
4739 }
4740
4741 if (mCurrentState.colorMatrix != colorMatrix) {
4742 mCurrentState.colorMatrix = colorMatrix;
4743 mCurrentState.colorMatrixChanged = true;
4744 setTransactionFlags(eTransactionNeeded);
4745 }
4746}
4747
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004748status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004749#pragma clang diagnostic push
4750#pragma clang diagnostic error "-Wswitch-enum"
4751 switch (static_cast<ISurfaceComposerTag>(code)) {
4752 // These methods should at minimum make sure that the client requested
4753 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004754 case BOOT_FINISHED:
4755 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004756 case CREATE_DISPLAY:
4757 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004758 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004759 case GET_ANIMATION_FRAME_STATS:
4760 case GET_HDR_CAPABILITIES:
4761 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004762 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004763 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004765 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004766 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004767 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004768 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004769 case GET_DISPLAYED_CONTENT_SAMPLE:
4770 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004771 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4772 IPCThreadState* ipc = IPCThreadState::self();
4773 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4774 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004775 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004776 }
Robert Carr1db73f62016-12-21 12:58:51 -08004777 return OK;
4778 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004779 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004780 IPCThreadState* ipc = IPCThreadState::self();
4781 const int pid = ipc->getCallingPid();
4782 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004783 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4784 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004785 return PERMISSION_DENIED;
4786 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004788 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004789 // Used by apps to hook Choreographer to SurfaceFlinger.
4790 case CREATE_DISPLAY_EVENT_CONNECTION:
4791 // The following calls are currently used by clients that do not
4792 // request necessary permissions. However, they do not expose any secret
4793 // information, so it is OK to pass them.
4794 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004795 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004797 case GET_PHYSICAL_DISPLAY_IDS:
4798 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004800 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801 case GET_DISPLAY_CONFIGS:
4802 case GET_DISPLAY_STATS:
4803 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4804 // Calling setTransactionState is safe, because you need to have been
4805 // granted a reference to Client* and Handle* to do anything with it.
4806 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004807 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004808 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004809 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004810 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004811 case IS_WIDE_COLOR_DISPLAY:
4812 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4813 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004814 return OK;
4815 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004816 case CAPTURE_LAYERS: {
4817 IPCThreadState* ipc = IPCThreadState::self();
4818 const int pid = ipc->getCallingPid();
4819 const int uid = ipc->getCallingUid();
4820 // allow media to capture layer for video thumbnails
4821 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4822 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4823 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4824 return PERMISSION_DENIED;
4825 }
4826 return OK;
4827 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004828 case CAPTURE_SCREEN:
4829 case ADD_REGION_SAMPLING_LISTENER:
4830 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004832 IPCThreadState* ipc = IPCThreadState::self();
4833 const int pid = ipc->getCallingPid();
4834 const int uid = ipc->getCallingUid();
4835 if ((uid != AID_GRAPHICS) &&
4836 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4837 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4838 return PERMISSION_DENIED;
4839 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 return OK;
4841 }
4842 // The following codes are deprecated and should never be allowed to access SF.
4843 case CONNECT_DISPLAY_UNUSED:
4844 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4845 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4846 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004847 }
chaviw93df2ea2019-04-30 16:45:12 -07004848 case CAPTURE_SCREEN_BY_ID: {
4849 IPCThreadState* ipc = IPCThreadState::self();
4850 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004851 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004852 return OK;
4853 }
4854 return PERMISSION_DENIED;
4855 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004857
4858 // These codes are used for the IBinder protocol to either interrogate the recipient
4859 // side of the transaction for its canonical interface descriptor or to dump its state.
4860 // We let them pass by default.
4861 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4862 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4863 code == IBinder::SYSPROPS_TRANSACTION) {
4864 return OK;
4865 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004866 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004867 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004868 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4870 return OK;
4871 }
4872 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4873 return PERMISSION_DENIED;
4874#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004875}
4876
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4878 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004879 status_t credentialCheck = CheckTransactCodeCredentials(code);
4880 if (credentialCheck != OK) {
4881 return credentialCheck;
4882 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004883
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4885 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004886 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004887 IPCThreadState* ipc = IPCThreadState::self();
4888 const int uid = ipc->getCallingUid();
4889 if (CC_UNLIKELY(uid != AID_SYSTEM
4890 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004891 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004892 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004893 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004894 return PERMISSION_DENIED;
4895 }
4896 int n;
4897 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004898 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004899 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 return NO_ERROR;
4901 case 1002: // SHOW_UPDATES
4902 n = data.readInt32();
4903 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004904 invalidateHwcGeometry();
4905 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004908 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004909 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004911 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004912 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004913 setTransactionFlags(
4914 eTransactionNeeded|
4915 eDisplayTransactionNeeded|
4916 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004917 return NO_ERROR;
4918 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004919 case 1006:{ // send empty update
4920 signalRefresh();
4921 return NO_ERROR;
4922 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004923 case 1008: // toggle use of hw composer
4924 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004925 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004926 invalidateHwcGeometry();
4927 repaintEverything();
4928 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004929 case 1009: // toggle use of transform hint
4930 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004931 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004932 invalidateHwcGeometry();
4933 repaintEverything();
4934 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004936 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004937 reply->writeInt32(0);
4938 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004939 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004940 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 return NO_ERROR;
4942 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004943 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944 if (!display) {
4945 return NAME_NOT_FOUND;
4946 }
4947
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004948 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004949 return NO_ERROR;
4950 }
4951 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004952 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004953 // daltonize
4954 n = data.readInt32();
4955 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004956 case 1:
4957 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4958 break;
4959 case 2:
4960 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4961 break;
4962 case 3:
4963 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4964 break;
4965 default:
4966 mDaltonizer.setType(ColorBlindnessType::None);
4967 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004968 }
4969 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004970 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004971 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004973 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004974
4975 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004976 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004978 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004980 // apply a color matrix
4981 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004983 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004984 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004985 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004987 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004989 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004991 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004992
4993 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4994 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004995 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004996 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4997 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4998 }
4999
Chia-I Wu28f320b2018-05-03 11:02:56 -07005000 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005001 return NO_ERROR;
5002 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005003 case 1016: { // Unused.
5004 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005005 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005006 case 1017: {
5007 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005008 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005009 return NO_ERROR;
5010 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005011 case 1018: { // Modify Choreographer's phase offset
5012 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005013 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005014 return NO_ERROR;
5015 }
5016 case 1019: { // Modify SurfaceFlinger's phase offset
5017 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005018 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005019 return NO_ERROR;
5020 }
Irvel468051e2016-06-13 16:44:44 -07005021 case 1020: { // Layer updates interceptor
5022 n = data.readInt32();
5023 if (n) {
5024 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005025 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005026 }
5027 else{
5028 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005029 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005030 }
5031 return NO_ERROR;
5032 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005033 case 1021: { // Disable HWC virtual displays
5034 n = data.readInt32();
5035 mUseHwcVirtualDisplays = !n;
5036 return NO_ERROR;
5037 }
Romain Guy0147a172017-06-01 13:53:56 -07005038 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005039 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005040 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005041
Chia-I Wu28f320b2018-05-03 11:02:56 -07005042 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005043 return NO_ERROR;
5044 }
Romain Guy54f154a2017-10-24 21:40:32 +01005045 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005046 int32_t colorMode;
5047
Chia-I Wu0d711262018-05-21 15:19:35 -07005048 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005049 if (data.readInt32(&colorMode) == NO_ERROR) {
5050 mForceColorMode = static_cast<ColorMode>(colorMode);
5051 }
Romain Guy54f154a2017-10-24 21:40:32 +01005052 invalidateHwcGeometry();
5053 repaintEverything();
5054 return NO_ERROR;
5055 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005056 // Deprecate, use 1030 to check whether the device is color managed.
5057 case 1024: {
5058 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005059 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005060 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005061 n = data.readInt32();
5062 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005063 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005064 Mutex::Autolock lock(mStateLock);
5065 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005066 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005067 reply->writeInt32(NO_ERROR);
5068 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005069 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005070 bool writeFile = false;
5071 {
5072 Mutex::Autolock lock(mStateLock);
5073 mTracingEnabledChanged = true;
5074 writeFile = mTracing.disable();
5075 }
5076
5077 if (writeFile) {
5078 reply->writeInt32(mTracing.writeToFile());
5079 } else {
5080 reply->writeInt32(NO_ERROR);
5081 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005082 }
5083 return NO_ERROR;
5084 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005085 case 1026: { // Get layer tracing status
5086 reply->writeBool(mTracing.isEnabled());
5087 return NO_ERROR;
5088 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005089 // Is a DisplayColorSetting supported?
5090 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091 const auto display = getDefaultDisplayDevice();
5092 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005093 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005094 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005095
5096 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5097 switch (setting) {
5098 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005099 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005100 break;
5101 case DisplayColorSetting::UNMANAGED:
5102 reply->writeBool(true);
5103 break;
5104 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005105 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005106 break;
5107 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005108 reply->writeBool(
5109 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005110 break;
5111 }
5112 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005113 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005114 // Is VrFlinger active?
5115 case 1028: {
5116 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005117 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005118 return NO_ERROR;
5119 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005120 // Set buffer size for SF tracing (value in KB)
5121 case 1029: {
5122 n = data.readInt32();
5123 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5124 ALOGW("Invalid buffer size: %d KB", n);
5125 reply->writeInt32(BAD_VALUE);
5126 return BAD_VALUE;
5127 }
5128
5129 ALOGD("Updating trace buffer to %d KB", n);
5130 mTracing.setBufferSize(n * 1024);
5131 reply->writeInt32(NO_ERROR);
5132 return NO_ERROR;
5133 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005134 // Is device color managed?
5135 case 1030: {
5136 reply->writeBool(useColorManagement);
5137 return NO_ERROR;
5138 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005139 // Override default composition data space
5140 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5141 // && adb shell stop zygote && adb shell start zygote
5142 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5143 // adb shell stop zygote && adb shell start zygote
5144 case 1031: {
5145 Mutex::Autolock _l(mStateLock);
5146 n = data.readInt32();
5147 if (n) {
5148 n = data.readInt32();
5149 if (n) {
5150 Dataspace dataspace = static_cast<Dataspace>(n);
5151 if (!validateCompositionDataspace(dataspace)) {
5152 return BAD_VALUE;
5153 }
5154 mDefaultCompositionDataspace = dataspace;
5155 }
5156 n = data.readInt32();
5157 if (n) {
5158 Dataspace dataspace = static_cast<Dataspace>(n);
5159 if (!validateCompositionDataspace(dataspace)) {
5160 return BAD_VALUE;
5161 }
5162 mWideColorGamutCompositionDataspace = dataspace;
5163 }
5164 } else {
5165 // restore composition data space.
5166 mDefaultCompositionDataspace = defaultCompositionDataspace;
5167 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5168 }
5169 return NO_ERROR;
5170 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005171 // Set trace flags
5172 case 1033: {
5173 n = data.readUint32();
5174 ALOGD("Updating trace flags to 0x%x", n);
5175 mTracing.setTraceFlags(n);
5176 reply->writeInt32(NO_ERROR);
5177 return NO_ERROR;
5178 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005179 case 1034: {
5180 // TODO(b/129297325): expose this via developer menu option
5181 n = data.readInt32();
5182 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005183 RefreshRateType type;
5184 {
5185 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5186 type = mDesiredActiveConfig.type;
5187 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005188 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005189 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005190 } else if (!n) {
5191 mRefreshRateOverlay.reset();
5192 }
5193 return NO_ERROR;
5194 }
Ady Abraham34392f72019-04-10 11:29:27 -07005195 case 1035: {
5196 n = data.readInt32();
5197 mDebugDisplayConfigSetByBackdoor = false;
5198 if (n >= 0) {
5199 const auto displayToken = getInternalDisplayToken();
5200 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5201 if (result != NO_ERROR) {
5202 return result;
5203 }
5204 mDebugDisplayConfigSetByBackdoor = true;
5205 }
5206 return NO_ERROR;
5207 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005208 }
5209 }
5210 return err;
5211}
5212
Steven Thomas6d8110b2017-08-31 18:24:21 -07005213void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005214 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005215 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005216}
5217
Ana Krulec7d1d6832018-12-27 11:10:09 -08005218void SurfaceFlinger::repaintEverythingForHWC() {
5219 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005220 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005221}
5222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005223// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5224class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005225public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005226 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5227 ~WindowDisconnector() {
5228 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005229 }
5230
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005231private:
5232 ANativeWindow* mWindow;
5233 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005234};
5235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005236status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005237 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5238 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005239 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005240 uint32_t reqWidth, uint32_t reqHeight,
5241 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005242 ISurfaceComposer::Rotation rotation,
5243 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005246 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005247
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005248 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5249
Chia-I Wu20261cb2018-08-23 12:55:44 -07005250 sp<DisplayDevice> display;
5251 {
5252 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005253
Chia-I Wu20261cb2018-08-23 12:55:44 -07005254 display = getDisplayDeviceLocked(displayToken);
5255 if (!display) return BAD_VALUE;
5256
Chia-I Wucb023152018-08-28 12:57:23 -07005257 // set the requested width/height to the logical display viewport size
5258 // by default
5259 if (reqWidth == 0 || reqHeight == 0) {
5260 reqWidth = uint32_t(display->getViewport().width());
5261 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005262 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005263 }
5264
Peiyong Lin0e003c92018-09-17 11:09:51 -07005265 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005266 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005267
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005268 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5269 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005270 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005271 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005272}
5273
chaviw93df2ea2019-04-30 16:45:12 -07005274static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5275 switch (colorMode) {
5276 case ColorMode::DISPLAY_P3:
5277 case ColorMode::BT2100_PQ:
5278 case ColorMode::BT2100_HLG:
5279 case ColorMode::DISPLAY_BT2020:
5280 return Dataspace::DISPLAY_P3;
5281 default:
5282 return Dataspace::V0_SRGB;
5283 }
5284}
5285
5286const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5287 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5288 if (displayToken) {
5289 return getDisplayDeviceLocked(displayToken);
5290 }
5291 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5292 // may not have a displayId.
5293 for (const auto& [token, display] : mDisplays) {
5294 if (display->getLayerStack() == displayOrLayerStack) {
5295 return display;
5296 }
5297 }
5298 return nullptr;
5299}
5300
5301status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5302 sp<GraphicBuffer>* outBuffer) {
5303 sp<DisplayDevice> display;
5304 uint32_t width;
5305 uint32_t height;
5306 ui::Transform::orientation_flags captureOrientation;
5307 {
5308 Mutex::Autolock _l(mStateLock);
5309 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5310 if (!display) {
5311 return BAD_VALUE;
5312 }
5313
5314 width = uint32_t(display->getViewport().width());
5315 height = uint32_t(display->getViewport().height());
5316
5317 captureOrientation = fromSurfaceComposerRotation(
5318 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005319 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5320 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5321 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5322 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5323 }
chaviw93df2ea2019-04-30 16:45:12 -07005324 *outDataspace =
5325 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5326 }
5327
5328 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5329 false /* captureSecureLayers */);
5330
5331 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5332 std::placeholders::_1);
5333 bool ignored = false;
5334 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5335 false /* useIdentityTransform */,
5336 ignored /* outCapturedSecureLayers */);
5337}
5338
Robert Carr866455f2019-04-02 16:28:26 -07005339status_t SurfaceFlinger::captureLayers(
5340 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5341 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5342 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5343 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005344 ATRACE_CALL();
5345
5346 class LayerRenderArea : public RenderArea {
5347 public:
Robert Carr578038f2018-03-09 12:25:24 -08005348 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005349 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5350 bool childrenOnly)
5351 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005352 mLayer(layer),
5353 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005354 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005355 mFlinger(flinger),
5356 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005357 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005358 Rect getBounds() const override {
5359 const Layer::State& layerState(mLayer->getDrawingState());
5360 return mLayer->getBufferSize(layerState);
5361 }
Marissa Wall61c58622018-07-18 10:12:20 -07005362 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005363 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005364 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005365 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005366 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005367 }
chaviwa76b2712017-09-20 12:02:26 -07005368 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005369 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005370 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005371 Rect getSourceCrop() const override {
5372 if (mCrop.isEmpty()) {
5373 return getBounds();
5374 } else {
5375 return mCrop;
5376 }
5377 }
Robert Carr578038f2018-03-09 12:25:24 -08005378 class ReparentForDrawing {
5379 public:
5380 const sp<Layer>& oldParent;
5381 const sp<Layer>& newParent;
5382
Vishnu Nair4351ad52019-02-11 14:13:02 -08005383 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5384 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005385 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005386 // Compute and cache the bounds for the new parent layer.
5387 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005388 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005389 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005390 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005391 };
5392
5393 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005394 const Rect sourceCrop = getSourceCrop();
5395 // no need to check rotation because there is none
5396 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5397 sourceCrop.height() != getReqHeight();
5398
Robert Carr578038f2018-03-09 12:25:24 -08005399 if (!mChildrenOnly) {
5400 mTransform = mLayer->getTransform().inverse();
5401 drawLayers();
5402 } else {
5403 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005404 // In the "childrenOnly" case we reparent the children to a screenshot
5405 // layer which has no properties set and which does not draw.
5406 sp<ContainerLayer> screenshotParentLayer =
5407 mFlinger->getFactory().createContainerLayer(
5408 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5409 bounds.getWidth(), bounds.getHeight(), 0,
5410 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005411
Vishnu Nair4351ad52019-02-11 14:13:02 -08005412 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005413 drawLayers();
5414 }
5415 }
chaviwa76b2712017-09-20 12:02:26 -07005416
chaviwa76b2712017-09-20 12:02:26 -07005417 private:
chaviw7206d492017-11-10 16:16:12 -08005418 const sp<Layer> mLayer;
5419 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005420
Peiyong Linefefaac2018-08-17 12:27:51 -07005421 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005422 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005423
5424 SurfaceFlinger* mFlinger;
5425 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005426 };
5427
Robert Carrc0df3122019-04-11 13:18:21 -07005428 int reqWidth = 0;
5429 int reqHeight = 0;
5430 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005431 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005432 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005433
Robert Carrc0df3122019-04-11 13:18:21 -07005434 {
5435 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005436
Robert Carrc0df3122019-04-11 13:18:21 -07005437 parent = fromHandle(layerHandleBinder);
5438 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5439 ALOGE("captureLayers called with an invalid or removed parent");
5440 return NAME_NOT_FOUND;
5441 }
5442
5443 const int uid = IPCThreadState::self()->getCallingUid();
5444 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5445 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5446 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5447 return PERMISSION_DENIED;
5448 }
5449
5450 if (sourceCrop.width() <= 0) {
5451 crop.left = 0;
5452 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5453 }
5454
5455 if (sourceCrop.height() <= 0) {
5456 crop.top = 0;
5457 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5458 }
5459 reqWidth = crop.width() * frameScale;
5460 reqHeight = crop.height() * frameScale;
5461
5462 for (const auto& handle : excludeHandles) {
5463 sp<Layer> excludeLayer = fromHandle(handle);
5464 if (excludeLayer != nullptr) {
5465 excludeLayers.emplace(excludeLayer);
5466 } else {
5467 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5468 return NAME_NOT_FOUND;
5469 }
5470 }
5471 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005472
Chia-I Wu20261cb2018-08-23 12:55:44 -07005473 // really small crop or frameScale
5474 if (reqWidth <= 0) {
5475 reqWidth = 1;
5476 }
5477 if (reqHeight <= 0) {
5478 reqHeight = 1;
5479 }
5480
Robert Carr866455f2019-04-02 16:28:26 -07005481 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5482 auto traverseLayers = [parent, childrenOnly,
5483 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005484 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5485 if (!layer->isVisible()) {
5486 return;
Robert Carr578038f2018-03-09 12:25:24 -08005487 } else if (childrenOnly && layer == parent.get()) {
5488 return;
chaviwa76b2712017-09-20 12:02:26 -07005489 }
Robert Carr866455f2019-04-02 16:28:26 -07005490
5491 sp<Layer> p = layer;
5492 while (p != nullptr) {
5493 if (excludeLayers.count(p) != 0) {
5494 return;
5495 }
5496 p = p->getParent();
5497 }
5498
chaviwa76b2712017-09-20 12:02:26 -07005499 visitor(layer);
5500 });
5501 };
Robert Carr108b2c72019-04-02 16:32:58 -07005502
5503 bool outCapturedSecureLayers = false;
5504 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5505 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005506}
5507
5508status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5509 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005510 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005511 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005512 bool useIdentityTransform,
5513 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005514 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005515
Peiyong Lin0e003c92018-09-17 11:09:51 -07005516 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005517 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5518 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005519 *outBuffer =
5520 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5521 static_cast<android_pixel_format>(reqPixelFormat), 1,
5522 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005523
Robert Carr108b2c72019-04-02 16:32:58 -07005524 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5525 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005526}
5527
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005528status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5529 TraverseLayersFunction traverseLayers,
5530 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005531 bool useIdentityTransform,
5532 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005533 // This mutex protects syncFd and captureResult for communication of the return values from the
5534 // main thread back to this Binder thread
5535 std::mutex captureMutex;
5536 std::condition_variable captureCondition;
5537 std::unique_lock<std::mutex> captureLock(captureMutex);
5538 int syncFd = -1;
5539 std::optional<status_t> captureResult;
5540
Robert Carr03480e22018-01-04 16:02:06 -08005541 const int uid = IPCThreadState::self()->getCallingUid();
5542 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5543
Dominik Laskowski8c001672018-05-30 16:52:06 -07005544 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 // If there is a refresh pending, bug out early and tell the binder thread to try again
5546 // after the refresh.
5547 if (mRefreshPending) {
5548 ATRACE_NAME("Skipping screenshot for now");
5549 std::unique_lock<std::mutex> captureLock(captureMutex);
5550 captureResult = std::make_optional<status_t>(EAGAIN);
5551 captureCondition.notify_one();
5552 return;
5553 }
5554
5555 status_t result = NO_ERROR;
5556 int fd = -1;
5557 {
5558 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005559 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005560 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005561 useIdentityTransform, forSystem, &fd,
5562 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005563 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005564 }
5565
5566 {
5567 std::unique_lock<std::mutex> captureLock(captureMutex);
5568 syncFd = fd;
5569 captureResult = std::make_optional<status_t>(result);
5570 captureCondition.notify_one();
5571 }
5572 });
5573
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005574 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005575 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005576 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005577 while (*captureResult == EAGAIN) {
5578 captureResult.reset();
5579 result = postMessageAsync(message);
5580 if (result != NO_ERROR) {
5581 return result;
5582 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005583 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 }
5585 result = *captureResult;
5586 }
5587
5588 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005589 sync_wait(syncFd, -1);
5590 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005591 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005594}
5595
chaviwa76b2712017-09-20 12:02:26 -07005596void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005597 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005598 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5599 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005600 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005601
chaviwa76b2712017-09-20 12:02:26 -07005602 const auto reqWidth = renderArea.getReqWidth();
5603 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005604 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005605 const auto transform = renderArea.getTransform();
5606 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005607
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005608 renderengine::DisplaySettings clientCompositionDisplay;
5609 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005610
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005611 // assume that bounds are never offset, and that they are the same as the
5612 // buffer bounds.
5613 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005614 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005615 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005616
5617 // Now take into account the rotation flag. We append a transform that
5618 // rotates the layer stack about the origin, then translate by buffer
5619 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005620 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005621 int displacementX = 0;
5622 int displacementY = 0;
5623 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5624 switch (rotation) {
5625 case ui::Transform::ROT_90:
5626 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005627 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005628 break;
5629 case ui::Transform::ROT_180:
5630 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005631 displacementY = renderArea.getBounds().getWidth();
5632 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 break;
5634 case ui::Transform::ROT_270:
5635 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005636 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 break;
5638 default:
5639 break;
5640 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005641
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005642 // We need to transform the clipping window into the right spot.
5643 // First, rotate the clipping rectangle by the rotation hint to get the
5644 // right orientation
5645 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5646 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5647 const vec4 rotClipTL = rotMatrix * clipTL;
5648 const vec4 rotClipBR = rotMatrix * clipBR;
5649 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5650 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5651 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5652 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5653
5654 // Now reposition the clipping rectangle with the displacement vector
5655 // computed above.
5656 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 clientCompositionDisplay.clip =
5658 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5659 newClipRight + displacementX, newClipBottom + displacementY);
5660
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005662 clientCompositionDisplay.globalTransform =
5663 clipTransform * clientCompositionDisplay.globalTransform;
5664
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005665 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5666 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005667
chaviw50da5042018-04-09 13:49:37 -07005668 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005669
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005670 renderengine::LayerSettings fillLayer;
5671 fillLayer.source.buffer.buffer = nullptr;
5672 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5673 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5674 fillLayer.alpha = half(alpha);
5675 clientCompositionLayers.push_back(fillLayer);
5676
5677 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005678 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005679 const bool supportProtectedContent = false;
5680 Region clip(renderArea.getBounds());
5681 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5682 clip,
5683 useIdentityTransform,
5684 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5685 renderArea.isSecure(),
5686 supportProtectedContent,
5687 clearRegion,
5688 };
5689 auto result = layer->prepareClientComposition(targetSettings);
5690 if (result) {
5691 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005692 }
chaviwa76b2712017-09-20 12:02:26 -07005693 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694
5695 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005696 // Use an empty fence for the buffer fence, since we just created the buffer so
5697 // there is no need for synchronization with the GPU.
5698 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005700 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005701 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005702 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005703
5704 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005705}
5706
chaviwa76b2712017-09-20 12:02:26 -07005707status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5708 TraverseLayersFunction traverseLayers,
5709 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005710 bool useIdentityTransform, bool forSystem,
5711 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005712 ATRACE_CALL();
5713
chaviwa76b2712017-09-20 12:02:26 -07005714 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005715 outCapturedSecureLayers =
5716 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005717 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005718
Robert Carr03480e22018-01-04 16:02:06 -08005719 // We allow the system server to take screenshots of secure layers for
5720 // use in situations like the Screen-rotation animation and place
5721 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005722 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005723 ALOGW("FB is protected: PERMISSION_DENIED");
5724 return PERMISSION_DENIED;
5725 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005726 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005727 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005728}
5729
chaviw95ef3c42019-02-14 10:55:09 -08005730void SurfaceFlinger::setInputWindowsFinished() {
5731 Mutex::Autolock _l(mStateLock);
5732
5733 mPendingSyncInputWindows = false;
5734 mTransactionCV.broadcast();
5735}
chaviw5f21a5e2019-02-14 10:00:34 -08005736
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005737// ---------------------------------------------------------------------------
5738
Dan Stoza412903f2017-04-27 13:42:17 -07005739void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5740 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005741}
5742
Dan Stoza412903f2017-04-27 13:42:17 -07005743void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5744 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005745}
5746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005747void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005748 const LayerVector::Visitor& visitor) {
5749 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005750 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005751 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005752 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005753 continue;
5754 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005755 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005756 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005757 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005758 return;
5759 }
chaviwa76b2712017-09-20 12:02:26 -07005760 if (!layer->isVisible()) {
5761 return;
5762 }
5763 visitor(layer);
5764 });
5765 }
5766}
5767
Dominik Laskowski22488f62019-03-28 09:53:04 -07005768void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5769 const std::vector<int32_t>& allowedConfigs) {
5770 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005771 return;
5772 }
5773
5774 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005775 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08005776
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005777 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07005778 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005779 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005780 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005781 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005782 setDesiredActiveConfig(
5783 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005784 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005785 }
5786 }
Ady Abraham838de062019-02-04 10:24:03 -08005787}
5788
Dominik Laskowski22488f62019-03-28 09:53:04 -07005789status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005790 const std::vector<int32_t>& allowedConfigs) {
5791 ATRACE_CALL();
5792
Dominik Laskowski22488f62019-03-28 09:53:04 -07005793 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005794 return BAD_VALUE;
5795 }
5796
Ady Abraham34392f72019-04-10 11:29:27 -07005797 if (mDebugDisplayConfigSetByBackdoor) {
5798 // ignore this request as config is overridden by backdoor
5799 return NO_ERROR;
5800 }
5801
Ady Abraham838de062019-02-04 10:24:03 -08005802 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005803 const auto display = getDisplayDeviceLocked(displayToken);
5804 if (!display) {
5805 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5806 displayToken.get());
5807 } else if (display->isVirtual()) {
5808 ALOGW("Attempt to set allowed display configs for virtual display");
5809 } else {
5810 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5811 }
Ady Abraham838de062019-02-04 10:24:03 -08005812 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005813
Ady Abraham838de062019-02-04 10:24:03 -08005814 return NO_ERROR;
5815}
5816
Dominik Laskowski22488f62019-03-28 09:53:04 -07005817status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005818 std::vector<int32_t>* outAllowedConfigs) {
5819 ATRACE_CALL();
5820
Dominik Laskowski22488f62019-03-28 09:53:04 -07005821 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005822 return BAD_VALUE;
5823 }
5824
Dominik Laskowski22488f62019-03-28 09:53:04 -07005825 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005826
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005827 const auto display = getDisplayDeviceLocked(displayToken);
5828 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005829 return NAME_NOT_FOUND;
5830 }
5831
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005832 if (display->isPrimary()) {
5833 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5834 }
5835
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005836 return NO_ERROR;
5837}
5838
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005839void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005840 mFlinger->setInputWindowsFinished();
5841}
5842
Robert Carrc0df3122019-04-11 13:18:21 -07005843sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5844 BBinder *b = handle->localBinder();
5845 if (b == nullptr) {
5846 return nullptr;
5847 }
5848 auto it = mLayersByLocalBinderToken.find(b);
5849 if (it != mLayersByLocalBinderToken.end()) {
5850 return it->second.promote();
5851 }
5852 return nullptr;
5853}
5854
Alec Mouri4545a8a2019-08-08 20:05:32 -07005855void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5856 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5857}
5858
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005859} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005860
Mathias Agopian3f844832013-08-07 21:24:32 -07005861#if defined(__gl_h_)
5862#error "don't include gl/gl.h in this file"
5863#endif
5864
5865#if defined(__gl2_h_)
5866#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005867#endif