blob: 7f819dd9ce0b6c5f7d7e2e88b7a0f907fb27d454 [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/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070049#include <gui/DebugEGLImageTracker.h>
50
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070098#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700111#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700125using namespace std::string_literals;
126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700259 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700260 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700262 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700263 mPhaseOffsets(mFactory.createPhaseOffsets()),
264 mPendingSyncInputWindows(false) {}
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 Abrahamadb9a992019-09-19 21:21:55 +0000342 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
Dan Stozaec460082018-12-17 15:35:09 -0800359 property_get("debug.sf.luma_sampling", value, "1");
360 mLumaSampling = atoi(value);
361
Romain Guy11d63f42017-07-20 12:47:14 -0700362 // We should be reading 'persist.sys.sf.color_saturation' here
363 // but since /data may be encrypted, we need to wait until after vold
364 // comes online to attempt to read the property. The property is
365 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800366
367 if (useTrebleTestingOverride()) {
368 // Without the override SurfaceFlinger cannot connect to HIDL
369 // services that are not listed in the manifests. Considered
370 // deriving the setting from the set service name, but it
371 // would be brittle if the name that's not 'default' is used
372 // for production purposes later on.
373 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377void SurfaceFlinger::onFirstRef()
378{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800379 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380}
381
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700382SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383
Dan Stozac7014012014-02-14 15:03:43 -0800384void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385{
386 // the window manager died on us. prepare its eulogy.
387
Andy McFadden13a082e2012-08-24 10:16:42 -0700388 // restore initial conditions (default device unblank, etc)
389 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390
391 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700392 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393}
394
Robert Carr1db73f62016-12-21 12:58:51 -0800395static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700396 status_t err = client->initCheck();
397 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800398 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 }
Robert Carr1db73f62016-12-21 12:58:51 -0800400 return nullptr;
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
404 return initClient(new Client(this));
405}
406
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700407sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
408 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409{
410 class DisplayToken : public BBinder {
411 sp<SurfaceFlinger> flinger;
412 virtual ~DisplayToken() {
413 // no more references, this display must be terminated
414 Mutex::Autolock _l(flinger->mStateLock);
415 flinger->mCurrentState.displays.removeItem(this);
416 flinger->setTransactionFlags(eDisplayTransactionNeeded);
417 }
418 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700419 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700420 : flinger(flinger) {
421 }
422 };
423
424 sp<BBinder> token = new DisplayToken(this);
425
426 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700427 // Display ID is assigned when virtual display is allocated by HWC.
428 DisplayDeviceState state;
429 state.isSecure = secure;
430 state.displayName = displayName;
431 mCurrentState.displays.add(token, state);
432 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433 return token;
434}
435
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700436void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700437 Mutex::Autolock _l(mStateLock);
438
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
440 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 return;
443 }
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
446 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 ALOGE("destroyDisplay called for non-virtual display");
448 return;
449 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 mInterceptor->saveDisplayDeletion(state.sequenceId);
451 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 setTransactionFlags(eDisplayTransactionNeeded);
453}
454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
456 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800458 const auto internalDisplayId = getInternalDisplayIdLocked();
459 if (!internalDisplayId) {
460 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 }
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 std::vector<PhysicalDisplayId> displayIds;
464 displayIds.reserve(mPhysicalDisplayTokens.size());
465 displayIds.push_back(internalDisplayId->value);
466
467 for (const auto& [id, token] : mPhysicalDisplayTokens) {
468 if (id != *internalDisplayId) {
469 displayIds.push_back(id.value);
470 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473 return displayIds;
474}
475
476sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
477 Mutex::Autolock lock(mStateLock);
478 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479}
480
Ady Abraham37965d42018-11-01 13:43:32 -0700481status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
482 if (!outGetColorManagement) {
483 return BAD_VALUE;
484 }
485 *outGetColorManagement = useColorManagement;
486 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700487}
488
Lloyd Pique441d5042018-10-18 16:49:51 -0700489HWComposer& SurfaceFlinger::getHwComposer() const {
490 return mCompositionEngine->getHwComposer();
491}
492
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700493renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
494 return mCompositionEngine->getRenderEngine();
495}
496
Lloyd Pique70d91362018-10-18 16:02:55 -0700497compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
498 return *mCompositionEngine.get();
499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
Mikael Pessa90092f42019-08-26 17:22:04 -0700510 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700511
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 // wait patiently for the window manager death
513 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700514 mWindowManager = defaultServiceManager()->getService(name);
515 if (mWindowManager != 0) {
516 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 }
Robert Carr720e5062018-07-30 17:45:14 -0700518 sp<IBinder> input(defaultServiceManager()->getService(
519 String16("inputflinger")));
520 if (input == nullptr) {
521 ALOGE("Failed to link to input service");
522 } else {
523 mInputFlinger = interface_cast<IInputFlinger>(input);
524 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 if (mVrFlinger) {
527 mVrFlinger->OnBootFinished();
528 }
529
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531 // formerly we would just kill the process, but we now ask it to exit so it
532 // can choose where to stop the animation.
533 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700534
535 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
536 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
537 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700538
Ana Krulecbd6654b2019-02-15 15:18:15 -0800539 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 readPersistentProperties();
541 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800542
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700543 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
544 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800545 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
546 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800548 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549}
550
Dan Stoza436ccf32018-06-21 12:10:12 -0700551uint32_t SurfaceFlinger::getNewTexture() {
552 {
553 std::lock_guard lock(mTexturePoolMutex);
554 if (!mTexturePool.empty()) {
555 uint32_t name = mTexturePool.back();
556 mTexturePool.pop_back();
557 ATRACE_INT("TexturePoolSize", mTexturePool.size());
558 return name;
559 }
560
561 // The pool was too small, so increase it for the future
562 ++mTexturePoolSize;
563 }
564
565 // The pool was empty, so we need to get a new texture name directly using a
566 // blocking call to the main thread
567 uint32_t name = 0;
568 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
569 return name;
570}
571
Mathias Agopian3f844832013-08-07 21:24:32 -0700572void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700573 std::lock_guard lock(mTexturePoolMutex);
574 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
575 // to actually delete this or not based on mTexturePoolSize
576 mTexturePool.push_back(texture);
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700578}
579
Wei Wangf9b05ee2017-07-19 20:59:39 -0700580// Do not call property_set on main thread which will be blocked by init
581// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700583 ALOGI( "SurfaceFlinger's main thread ready to run. "
584 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700585 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900586
Steven Thomasb02664d2017-07-26 18:48:28 -0700587 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800588
Steven Thomasb02664d2017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700590 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800591 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d72019-10-09 10:39:09 -0700592 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
593 renderengine::RenderEngineCreationArgs::Builder()
594 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
595 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
596 .setUseColorManagerment(useColorManagement)
597 .setEnableProtectedContext(enable_protected_contents(false))
598 .setPrecacheToneMapperShaderOnly(false)
599 .setContextPriority(useContextPriority
600 ? renderengine::RenderEngine::ContextPriority::HIGH
601 : renderengine::RenderEngine::ContextPriority::MEDIUM)
602 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800603 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700604
605 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
606 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700607 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
608 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800609 // Process any initial hotplug and resulting display changes.
610 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700611 const auto display = getDefaultDisplayDeviceLocked();
612 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700614 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800615
Steven Thomas050b2c82017-03-06 11:45:16 -0800616 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700617 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700618 // This callback is called from the vr flinger dispatch thread. We
619 // need to call signalTransaction(), which requires holding
620 // mStateLock when we're not on the main thread. Acquiring
621 // mStateLock from the vr flinger dispatch thread might trigger a
622 // deadlock in surface flinger (see b/66916578), so post a message
623 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700624 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700625 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
626 mVrFlingerRequestsDisplay = requestDisplay;
627 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800629 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700630 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
631 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700632 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 .value_or(0),
634 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (!mVrFlinger) {
636 ALOGE("Failed to start vrflinger");
637 }
638 }
639
Mathias Agopian92a979a2012-08-02 18:32:23 -0700640 // initialize our drawing state
641 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700642
Andy McFadden13a082e2012-08-24 10:16:42 -0700643 // set initial conditions (e.g. unblank default device)
644 initializeDisplays();
645
Steven Thomas137d4bc2019-07-25 16:55:14 -0700646 char primeShaderCache[PROPERTY_VALUE_MAX];
647 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
648 if (atoi(primeShaderCache)) {
649 getRenderEngine().primeCache();
650 }
Dan Stoza4e637772016-07-28 13:31:51 -0700651
Wei Wangf9b05ee2017-07-19 20:59:39 -0700652 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700653
654 const bool presentFenceReliable =
655 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
656 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657
658 if (mStartPropertySetThread->Start() != NO_ERROR) {
659 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800660 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700663}
664
Romain Guy11d63f42017-07-20 12:47:14 -0700665void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700666 Mutex::Autolock _l(mStateLock);
667
Romain Guy11d63f42017-07-20 12:47:14 -0700668 char value[PROPERTY_VALUE_MAX];
669
670 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800671 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700672 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800673 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100674
675 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700676 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800677
678 property_get("persist.sys.sf.color_mode", value, "0");
679 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700680}
681
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Start boot animation service by setting a property mailbox
684 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 if (mStartPropertySetThread->join() != NO_ERROR) {
688 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800689 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700693 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700697 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800701
Jamie Gennis582270d2011-08-17 18:19:00 -0700702bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800704 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800705 return authenticateSurfaceTextureLocked(bufferProducer);
706}
707
708bool SurfaceFlinger::authenticateSurfaceTextureLocked(
709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800710 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800711 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800712}
713
Brian Anderson6b376712017-04-04 10:51:39 -0700714status_t SurfaceFlinger::getSupportedFrameTimestamps(
715 std::vector<FrameEvent>* outSupported) const {
716 *outSupported = {
717 FrameEvent::REQUESTED_PRESENT,
718 FrameEvent::ACQUIRE,
719 FrameEvent::LATCH,
720 FrameEvent::FIRST_REFRESH_START,
721 FrameEvent::LAST_REFRESH_START,
722 FrameEvent::GPU_COMPOSITION_DONE,
723 FrameEvent::DEQUEUE_READY,
724 FrameEvent::RELEASE,
725 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700726 ConditionalLock _l(mStateLock,
727 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700728 if (!getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
731 }
732 return NO_ERROR;
733}
734
Dominik Laskowski22488f62019-03-28 09:53:04 -0700735status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
736 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700737 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 return BAD_VALUE;
739 }
740
Dominik Laskowski22488f62019-03-28 09:53:04 -0700741 Mutex::Autolock lock(mStateLock);
742
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800743 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700744 if (!displayId) {
745 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700746 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748 // TODO: Not sure if display density should handled by SF any longer
749 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700750 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700752 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800753 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700754 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755 }
756 return density;
757 }
758 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700759 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700761 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 return getDensityFromProperty("ro.sf.lcd_density"); }
763 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700764
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700766
Dominik Laskowski075d3172018-05-24 15:50:06 -0700767 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700768 DisplayInfo info = DisplayInfo();
769
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 float xdpi = hwConfig->getDpiX();
771 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700772
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700773 info.w = hwConfig->getWidth();
774 info.h = hwConfig->getHeight();
775 // Default display viewport to display width and height
776 info.viewportW = info.w;
777 info.viewportH = info.h;
778
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800779 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 // The density of the device is provided by a build property
781 float density = Density::getBuildDensity() / 160.0f;
782 if (density == 0) {
783 // the build doesn't provide a density -- this is wrong!
784 // use xdpi instead
785 ALOGE("ro.sf.lcd_density must be defined as a build property");
786 density = xdpi / 160.0f;
787 }
788 if (Density::getEmuDensity()) {
789 // if "qemu.sf.lcd_density" is specified, it overrides everything
790 xdpi = ydpi = density = Density::getEmuDensity();
791 density /= 160.0f;
792 }
793 info.density = density;
794
795 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 const auto display = getDefaultDisplayDeviceLocked();
797 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700798
799 // This is for screenrecord
800 const Rect viewport = display->getViewport();
801 if (viewport.isValid()) {
802 info.viewportW = uint32_t(viewport.getWidth());
803 info.viewportH = uint32_t(viewport.getHeight());
804 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700805 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 } else {
807 // TODO: where should this value come from?
808 static const int TV_DENSITY = 213;
809 info.density = TV_DENSITY / 160.0f;
810 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700811
812 const auto display = getDisplayDeviceLocked(displayToken);
813 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 }
815
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 info.xdpi = xdpi;
817 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800819
820 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700821 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822
Andy McFadden91b2ca82014-06-13 14:04:23 -0700823 // This is how far in advance a buffer must be queued for
824 // presentation at a given time. If you want a buffer to appear
825 // on the screen at time N, you must submit the buffer before
826 // (N - presentationDeadline).
827 //
828 // Normally it's one full refresh period (to give SF a chance to
829 // latch the buffer), but this can be reduced by configuring a
830 // DispSync offset. Any additional delays introduced by the hardware
831 // composer or panel must be accounted for here.
832 //
833 // We add an additional 1ms to allow for processing time and
834 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700835 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
837 // All non-virtual displays are currently considered secure.
838 info.secure = true;
839
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800840 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700841 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800842 std::swap(info.w, info.h);
843 }
844
Michael Wright28f24d02016-07-12 13:30:53 -0700845 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 }
847
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 return NO_ERROR;
849}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700850
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700851status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
852 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700853 return BAD_VALUE;
854 }
855
Ana Krulecc2870422019-01-29 19:00:58 -0800856 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700857 return NO_ERROR;
858}
859
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700860int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
861 const auto display = getDisplayDevice(displayToken);
862 if (!display) {
863 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800864 return BAD_VALUE;
865 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700866
Steven Thomasc9098452019-09-30 17:15:05 -0700867 if (display->isPrimary()) {
868 std::lock_guard<std::mutex> lock(mActiveConfigLock);
869 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800870 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700871 }
Steven Thomasc9098452019-09-30 17:15:05 -0700872 }
Ady Abraham2139f732019-11-13 18:56:40 -0800873
874 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700875}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700876
Ady Abraham03b02dd2019-03-21 15:40:11 -0700877void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800878 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800879 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
880 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800881
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800882 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800883 // config twice. However event generation config might have changed so we need to update it
884 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800885 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700886 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
887 mDesiredActiveConfig = info;
888 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800889
890 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800891 // This will trigger HWC refresh without resetting the idle timer.
892 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700893 // Start receiving vsync samples now, so that we can detect a period
894 // switch.
895 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700896 // As we called to set period, we will call to onRefreshRateChangeCompleted once
897 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700898 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800899
900 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700901 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800902 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800903 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700904
905 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800906 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700907 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800908}
909
910status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
911 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800912
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100913 if (!displayToken) {
914 return BAD_VALUE;
915 }
Ady Abraham838de062019-02-04 10:24:03 -0800916
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100917 status_t result = NO_ERROR;
918
919 postMessageSync(new LambdaMessage([&]() {
920 const auto display = getDisplayDeviceLocked(displayToken);
921 if (!display) {
922 ALOGE("Attempt to set allowed display configs for invalid display token %p",
923 displayToken.get());
924 result = BAD_VALUE;
925 } else if (display->isVirtual()) {
926 ALOGW("Attempt to set allowed display configs for virtual display");
927 result = BAD_VALUE;
928 } else {
929 HwcConfigIndexType config(mode);
930 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
931 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
932 refreshRate.fps);
933 }
934 }));
935
936 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937}
938
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800939void SurfaceFlinger::setActiveConfigInternal() {
940 ATRACE_CALL();
941
Dominik Laskowski22488f62019-03-28 09:53:04 -0700942 const auto display = getDefaultDisplayDeviceLocked();
943 if (!display) {
944 return;
945 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946
Dominik Laskowski22488f62019-03-28 09:53:04 -0700947 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800948 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700949 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800950 display->setActiveConfig(mUpcomingActiveConfig.configId);
951
Ady Abraham2139f732019-11-13 18:56:40 -0800952 auto refreshRate =
953 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
954 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700955 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800956 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700957
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800958 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800959 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
960 mUpcomingActiveConfig.configId);
961 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962}
963
Ady Abraham53852a52019-05-28 18:07:44 -0700964void SurfaceFlinger::desiredActiveConfigChangeDone() {
965 std::lock_guard<std::mutex> lock(mActiveConfigLock);
966 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
967 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700968
969 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800970 auto refreshRate =
971 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
972 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700973 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700974}
975
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800977 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800978 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700980 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700982 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 return true;
984 }
985
986 // We received the present fence from the HWC, so we assume it successfully updated
987 // the config, hence we update SF.
988 mCheckPendingFence = false;
989 setActiveConfigInternal();
990 }
991
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992 // Store the local variable to release the lock.
993 ActiveConfigInfo desiredActiveConfig;
994 {
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996 if (!mDesiredActiveConfigChanged) {
997 return false;
998 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 desiredActiveConfig = mDesiredActiveConfig;
1000 }
1001
Ady Abraham2139f732019-11-13 18:56:40 -08001002 auto refreshRate =
1003 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1004 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1005 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1008 // display is not valid or we are already in the requested mode
1009 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001010 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013
Ady Abraham838de062019-02-04 10:24:03 -08001014 // Desired active config was set, it is different than the config currently in use, however
1015 // allowed configs might have change by the time we process the refresh.
1016 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001017 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001018 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001019 return false;
1020 }
Alec Mouri7f015182019-07-11 13:56:22 -07001021
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022 mUpcomingActiveConfig = desiredActiveConfig;
1023 const auto displayId = display->getId();
1024 LOG_ALWAYS_FATAL_IF(!displayId);
1025
Ady Abraham2139f732019-11-13 18:56:40 -08001026 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001027
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001028 // TODO(b/142753666) use constrains
1029 HWC2::VsyncPeriodChangeConstraints constraints;
1030 constraints.desiredTimeNanos = systemTime();
1031 constraints.seamlessRequired = false;
1032
1033 HWC2::VsyncPeriodChangeTimeline outTimeline;
1034 auto status =
1035 getHwComposer().setActiveConfigWithConstraints(*displayId,
1036 mUpcomingActiveConfig.configId.value(),
1037 constraints, &outTimeline);
1038 if (status != NO_ERROR) {
1039 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1040 return false;
1041 }
1042
1043 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1044 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001047}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1050 Vector<ColorMode>* outColorModes) {
1051 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return BAD_VALUE;
1053 }
1054
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001056 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001057 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001058 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1059
1060 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1061 if (!displayId) {
1062 return NAME_NOT_FOUND;
1063 }
1064
Dominik Laskowski075d3172018-05-24 15:50:06 -07001065 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001066 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 }
Michael Wright28f24d02016-07-12 13:30:53 -07001068 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001069
1070 // If it's built-in display and the configuration claims it's not wide color capable,
1071 // filter out all wide color modes. The typical reason why this happens is that the
1072 // hardware is not good enough to support GPU composition of wide color, and thus the
1073 // OEMs choose to disable this capability.
1074 if (isInternalDisplay && !hasWideColorDisplay) {
1075 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1076 isWideColorMode);
1077 } else {
1078 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080
1081 return NO_ERROR;
1082}
1083
Daniel Solomon42d04562019-01-20 21:03:19 -08001084status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1085 ui::DisplayPrimaries &primaries) {
1086 if (!displayToken) {
1087 return BAD_VALUE;
1088 }
1089
1090 // Currently we only support this API for a single internal display.
1091 if (getInternalDisplayToken() != displayToken) {
1092 return BAD_VALUE;
1093 }
1094
1095 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1096 return NO_ERROR;
1097}
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1100 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001101 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001102 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001103 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001104}
1105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001107 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 Vector<ColorMode> modes;
1109 getDisplayColorModes(displayToken, &modes);
1110 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1111 if (mode < ColorMode::NATIVE || !exists) {
1112 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1113 decodeColorMode(mode).c_str(), mode, displayToken.get());
1114 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001115 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const auto display = getDisplayDevice(displayToken);
1117 if (!display) {
1118 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1119 decodeColorMode(mode).c_str(), mode, displayToken.get());
1120 } else if (display->isVirtual()) {
1121 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1122 decodeColorMode(mode).c_str(), mode);
1123 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001124 display->getCompositionDisplay()->setColorProfile(
1125 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1126 RenderIntent::COLORIMETRIC,
1127 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 }
1129 }));
1130
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return NO_ERROR;
1132}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001133
Galia Peycheva5492cb52019-10-30 14:13:16 +01001134status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1135 bool* outSupport) const {
1136 Mutex::Autolock _l(mStateLock);
1137
1138 if (!displayToken) {
1139 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1140 return BAD_VALUE;
1141 }
1142 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1143 if (!displayId) {
1144 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1145 displayToken.get());
1146 return NAME_NOT_FOUND;
1147 }
1148 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1149 HWC2::DisplayCapability::AutoLowLatencyMode);
1150 return NO_ERROR;
1151}
1152
1153void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1154 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1155}
1156
1157void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1158 if (!displayToken) {
1159 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1160 return;
1161 }
1162 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1163 if (!displayId) {
1164 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1165 displayToken.get());
1166 return;
1167 }
1168
1169 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1170}
1171
1172status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1173 bool* outSupport) const {
1174 Mutex::Autolock _l(mStateLock);
1175
1176 if (!displayToken) {
1177 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1178 return BAD_VALUE;
1179 }
1180 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1181 if (!displayId) {
1182 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1183 displayToken.get());
1184 return NAME_NOT_FOUND;
1185 }
1186
1187 std::vector<HWC2::ContentType> outSupportedContentTypes;
1188 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1189 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1190 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1191 return NO_ERROR;
1192}
1193
1194void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1195 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1196}
1197
1198void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1199 if (!displayToken) {
1200 ALOGE("setGameContentType() failed. Missing display token.");
1201 return;
1202 }
1203 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1204 if (!displayId) {
1205 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1206 displayToken.get());
1207 return;
1208 }
1209
1210 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1211 getHwComposer().setContentType(*displayId, type);
1212}
1213
Svetoslavd85084b2014-03-20 10:28:31 -07001214status_t SurfaceFlinger::clearAnimationFrameStats() {
1215 Mutex::Autolock _l(mStateLock);
1216 mAnimFrameTracker.clearStats();
1217 return NO_ERROR;
1218}
1219
1220status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1221 Mutex::Autolock _l(mStateLock);
1222 mAnimFrameTracker.getStats(outStats);
1223 return NO_ERROR;
1224}
1225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001226status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1227 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001228 Mutex::Autolock _l(mStateLock);
1229
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001230 const auto display = getDisplayDeviceLocked(displayToken);
1231 if (!display) {
1232 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001233 return BAD_VALUE;
1234 }
1235
Peiyong Linfb069302018-04-25 14:34:31 -07001236 // At this point the DisplayDeivce should already be set up,
1237 // meaning the luminance information is already queried from
1238 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001239 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001240 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1241 capabilities.getDesiredMaxLuminance(),
1242 capabilities.getDesiredMaxAverageLuminance(),
1243 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001244
1245 return NO_ERROR;
1246}
1247
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001248status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1249 ui::PixelFormat* outFormat,
1250 ui::Dataspace* outDataspace,
1251 uint8_t* outComponentMask) const {
1252 if (!outFormat || !outDataspace || !outComponentMask) {
1253 return BAD_VALUE;
1254 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001255 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001256 if (!display || !display->getId()) {
1257 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1258 return BAD_VALUE;
1259 }
1260 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1261 outDataspace, outComponentMask);
1262}
1263
Kevin DuBois74e53772018-11-19 10:52:38 -08001264status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1265 bool enable, uint8_t componentMask,
1266 uint64_t maxFrames) const {
1267 const auto display = getDisplayDevice(displayToken);
1268 if (!display || !display->getId()) {
1269 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1270 return BAD_VALUE;
1271 }
1272
1273 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1274 componentMask, maxFrames);
1275}
1276
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001277status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1278 uint64_t maxFrames, uint64_t timestamp,
1279 DisplayedFrameStats* outStats) const {
1280 const auto display = getDisplayDevice(displayToken);
1281 if (!display || !display->getId()) {
1282 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1283 return BAD_VALUE;
1284 }
1285
1286 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1287 outStats);
1288}
1289
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001290status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1291 if (!outSupported) {
1292 return BAD_VALUE;
1293 }
1294 *outSupported = getRenderEngine().supportsProtectedContent();
1295 return NO_ERROR;
1296}
1297
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001298status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1299 bool* outIsWideColorDisplay) const {
1300 if (!displayToken || !outIsWideColorDisplay) {
1301 return BAD_VALUE;
1302 }
1303 Mutex::Autolock _l(mStateLock);
1304 const auto display = getDisplayDeviceLocked(displayToken);
1305 if (!display) {
1306 return BAD_VALUE;
1307 }
Peiyong Linff84a152019-05-17 18:36:19 -07001308
1309 // Use hasWideColorDisplay to override built-in display.
1310 const auto displayId = display->getId();
1311 if (displayId && displayId == getInternalDisplayIdLocked()) {
1312 *outIsWideColorDisplay = hasWideColorDisplay;
1313 return NO_ERROR;
1314 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001315 *outIsWideColorDisplay = display->hasWideColorGamut();
1316 return NO_ERROR;
1317}
1318
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001319status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001320 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001321 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001322
Dominik Laskowski6505f792019-09-18 11:10:05 -07001323 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1324 mEventQueue->setEventConnection(
1325 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001326 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001327 }));
1328
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001329 return NO_ERROR;
1330}
1331
1332status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001333 Mutex::Autolock lock(mStateLock);
1334 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001335}
1336
Lloyd Pique755e3192018-01-31 16:46:15 -08001337status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1338 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001339 // Try to acquire a lock for 1s, fail gracefully
1340 const status_t err = mStateLock.timedLock(s2ns(1));
1341 const bool locked = (err == NO_ERROR);
1342 if (!locked) {
1343 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1344 return TIMED_OUT;
1345 }
1346
1347 outLayers->clear();
1348 mCurrentState.traverseInZOrder([&](Layer* layer) {
1349 outLayers->push_back(layer->getLayerDebugInfo());
1350 });
1351
1352 mStateLock.unlock();
1353 return NO_ERROR;
1354}
1355
Peiyong Linc6780972018-10-28 15:24:08 -07001356status_t SurfaceFlinger::getCompositionPreference(
1357 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1358 Dataspace* outWideColorGamutDataspace,
1359 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001360 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001361 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001362 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001363 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001364 return NO_ERROR;
1365}
1366
Dan Stozaec460082018-12-17 15:35:09 -08001367status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1368 const sp<IBinder>& stopLayerHandle,
1369 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001370 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001371 return BAD_VALUE;
1372 }
1373 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001374 return NO_ERROR;
1375}
1376
Dan Stozaec460082018-12-17 15:35:09 -08001377status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001378 if (!listener) {
1379 return BAD_VALUE;
1380 }
Dan Stozaec460082018-12-17 15:35:09 -08001381 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001382 return NO_ERROR;
1383}
Dan Gittik57e63c52019-01-18 16:37:54 +00001384
1385status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1386 bool* outSupport) const {
1387 if (!displayToken || !outSupport) {
1388 return BAD_VALUE;
1389 }
1390 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1391 if (!displayId) {
1392 return NAME_NOT_FOUND;
1393 }
1394 *outSupport =
1395 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1396 return NO_ERROR;
1397}
1398
1399status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1400 float brightness) const {
1401 if (!displayToken) {
1402 return BAD_VALUE;
1403 }
1404 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1405 if (!displayId) {
1406 return NAME_NOT_FOUND;
1407 }
1408 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1409}
1410
Ady Abraham8532d012019-05-08 14:50:56 -07001411status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1412 PowerHint powerHint = static_cast<PowerHint>(hintId);
1413
1414 if (powerHint == PowerHint::INTERACTION) {
1415 mScheduler->notifyTouchEvent();
1416 }
1417
1418 return NO_ERROR;
1419}
1420
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001421// ----------------------------------------------------------------------------
1422
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001423sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001424 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001425 const auto& handle =
1426 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001427
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001428 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001429}
1430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001431// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432
1433void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001434 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001435}
1436
1437void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001438 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001439 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001440}
1441
1442void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001443 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001444 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001445}
1446
1447void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001448 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001449 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450}
1451
1452status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001453 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001454 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455}
1456
1457status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001458 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001459 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 if (res == NO_ERROR) {
1461 msg->wait();
1462 }
1463 return res;
1464}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001465
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001466void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001467 do {
1468 waitForEvent();
1469 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470}
1471
Dominik Laskowski83b88212018-12-11 13:34:06 -08001472nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001473 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001474 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1475 return 0;
1476 }
1477
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001478 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001479}
1480
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001481void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001482 int64_t timestamp,
1483 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001484 ATRACE_NAME("SF onVsync");
1485
Ady Abraham7159f572019-10-11 11:10:18 -07001486 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1487
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001490 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 return;
1492 }
1493
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001495 return;
1496 }
1497
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001499 // For now, we don't do anything with external display vsyncs.
1500 return;
1501 }
1502
Alec Mourif8e689c2019-05-20 18:32:22 -07001503 bool periodFlushed = false;
1504 mScheduler->addResyncSample(timestamp, &periodFlushed);
1505 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001506 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001507 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001508}
1509
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001511 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1512 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513}
1514
Ady Abraham2139f732019-11-13 18:56:40 -08001515bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001516 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001517}
1518
Ady Abraham2139f732019-11-13 18:56:40 -08001519void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1520 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001521 const auto display = getDefaultDisplayDeviceLocked();
1522 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001523 return;
1524 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001525 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001526
Ana Krulec7d1d6832018-12-27 11:10:09 -08001527 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001528 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1529 ALOGV("Skipping config %d as it is not part of allowed configs",
1530 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001531 return;
1532 }
1533
Ady Abraham2139f732019-11-13 18:56:40 -08001534 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001535}
1536
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001537void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001538 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001539 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001540 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541
Lloyd Piqueba04e622017-12-14 17:11:26 -08001542 // Ignore events that do not have the right sequenceId.
1543 if (sequenceId != getBE().mComposerSequenceId) {
1544 return;
1545 }
1546
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 // Only lock if we're not on the main thread. This function is normally
1548 // called on a hwbinder thread, but for the primary display it's called on
1549 // the main thread with the state lock already held, so don't attempt to
1550 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001551 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001552
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001553 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001554
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001555 if (std::this_thread::get_id() == mMainThreadId) {
1556 // Process all pending hot plug events immediately if we are on the main thread.
1557 processDisplayHotplugEventsLocked();
1558 }
1559
Lloyd Piqueba04e622017-12-14 17:11:26 -08001560 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001561}
1562
Ady Abraham7159f572019-10-11 11:10:18 -07001563void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001564 int32_t sequenceId, hwc2_display_t /*display*/,
1565 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1566 Mutex::Autolock lock(mStateLock);
1567 if (sequenceId != getBE().mComposerSequenceId) {
1568 return;
1569 }
1570 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001571}
1572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001574 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001575 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001577 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001578 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001579}
1580
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001581void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001582 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001583
1584 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1585 // display power state.
1586 postMessageAsync(new LambdaMessage(
1587 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1588}
1589
1590void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1591 ATRACE_CALL();
1592
Ady Abraham27c70212019-06-11 10:52:26 -07001593 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1594
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001595 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001596 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1597 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001598 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001599 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001600 }
Mathias Agopian86303202012-07-24 22:46:10 -07001601}
1602
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001603// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001604void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001605 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001606 // Clear the drawing state so that the logic inside of
1607 // handleTransactionLocked will fire. It will determine the delta between
1608 // mCurrentState and mDrawingState and re-apply all changes when we make the
1609 // transition.
1610 mDrawingState.displays.clear();
1611 mDisplays.clear();
1612}
1613
Steven Thomas050b2c82017-03-06 11:45:16 -08001614void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001615 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001616 if (!mVrFlinger)
1617 return;
1618 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001619 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 return;
1621 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 ALOGE("Vr flinger is only supported for remote hardware composer"
1625 " service connections. Ignoring request to transition to vr"
1626 " flinger.");
1627 mVrFlingerRequestsDisplay = false;
1628 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001629 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632
Steven Thomas0123ac62018-07-12 11:32:34 -07001633 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001634 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001635
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001636 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001637
1638 // Clear out all the output layers from the composition engine for all
1639 // displays before destroying the hardware composer interface. This ensures
1640 // any HWC layers are destroyed through that interface before it becomes
1641 // invalid.
1642 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001643 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001644 }
1645
Steven Thomas0123ac62018-07-12 11:32:34 -07001646 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1647 // called below. Clear the reference now so we don't accidentally use it
1648 // later.
1649 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Steven Thomasb02664d2017-07-26 18:48:28 -07001651 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001653 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654
Steven Thomasb02664d2017-07-26 18:48:28 -07001655 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001656 // Delete the current instance before creating the new one
1657 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1658 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1659 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1660 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001661
Lloyd Pique441d5042018-10-18 16:49:51 -07001662 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001663 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001664
1665 if (vrFlingerRequestsDisplay) {
1666 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001667 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001668
1669 mVisibleRegionsDirty = true;
1670 invalidateHwcGeometry();
1671
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001672 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001673 display = getDefaultDisplayDeviceLocked();
1674 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001675 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001676
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001678 const nsecs_t vsyncPeriod = getVsyncPeriod();
1679 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001680
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001681 // The present fences returned from vr_hwc are not an accurate
1682 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001683 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001684
Steven Thomasb02664d2017-07-26 18:48:28 -07001685 // Use phase of 0 since phase is not known.
1686 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001687 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001688 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001689
Ana Krulecc2870422019-01-29 19:00:58 -08001690 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001691
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001692 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001693 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001694}
1695
Ady Abraham11579302019-09-19 12:35:58 -07001696bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1697 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001698 // We are storing the last 2 present fences. If sf's phase offset is to be
1699 // woken up before the actual vsync but targeting the next vsync, we need to check
1700 // fence N-2
1701 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001702 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001703 ? mPreviousPresentFences[0]
1704 : mPreviousPresentFences[1];
1705
Ady Abraham11579302019-09-19 12:35:58 -07001706 if (fence == Fence::NO_FENCE) {
1707 return false;
1708 }
1709
1710 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1711 fence->wait(graceTimeMs);
1712 }
1713
1714 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001715}
1716
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001717void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001718 DisplayStatInfo stats;
1719 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001720 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001721 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001722 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001723 mPhaseOffsets->getOffsetThresholdForNextVsync()
1724 ? presentTime
1725 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001726}
1727
Dominik Laskowski22488f62019-03-28 09:53:04 -07001728void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001729 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001730 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001732 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001733 // calculate the expected present time once and use the cached
1734 // value throughout this frame to make sure all layers are
1735 // seeing this same value.
1736 populateExpectedPresentTime();
1737
Ady Abraham11579302019-09-19 12:35:58 -07001738 // When Backpressure propagation is enabled we want to give a small grace period
1739 // for the present fence to fire instead of just giving up on this frame to handle cases
1740 // where present fence is just about to get signaled.
1741 const int graceTimeForPresentFenceMs =
1742 (mPropagateBackpressure &&
1743 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1744 ? 1
1745 : 0;
1746 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1747 previousFrameMissed(
1748 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001749 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1750 mHadDeviceComposition && frameMissed};
1751 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1752 mHadClientComposition && frameMissed};
1753
Alec Mouricc0fc602019-02-26 21:45:19 -08001754 if (frameMissed) {
1755 mFrameMissedCount++;
1756 mTimeStats->incrementMissedFrames();
1757 }
1758
Alec Mouri40189b02019-03-05 15:07:54 -08001759 if (hwcFrameMissed) {
1760 mHwcFrameMissedCount++;
1761 }
1762
1763 if (gpuFrameMissed) {
1764 mGpuFrameMissedCount++;
1765 }
1766
Dominik Laskowski49cea512019-11-12 14:13:23 -08001767 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001768
Ady Abrahamb838aed2019-02-12 15:30:16 -08001769 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001770 break;
1771 }
1772
Ady Abrahamadb9a992019-09-19 21:21:55 +00001773 if (frameMissed && mPropagateBackpressure) {
1774 if ((hwcFrameMissed && !gpuFrameMissed) ||
1775 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001776 signalLayerUpdate();
1777 break;
1778 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001779 }
Dan Stoza50182882016-07-08 12:02:20 -07001780
Steven Thomas050b2c82017-03-06 11:45:16 -08001781 // Now that we're going to make it to the handleMessageTransaction()
1782 // call below it's safe to call updateVrFlinger(), which will
1783 // potentially trigger a display handoff.
1784 updateVrFlinger();
1785
Dan Stoza6b9454d2014-11-07 16:00:59 -08001786 bool refreshNeeded = handleMessageTransaction();
1787 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001788
1789 updateCursorAsync();
1790 updateInputFlinger();
1791
Dan Stoza58784442014-12-02 16:58:17 -08001792 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001793 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001794 // Signal a refresh if a transaction modified the window state,
1795 // a new buffer was latched, or if HWC has requested a full
1796 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001797 if (mFrameStartTime <= 0) {
1798 // We should only use the time of the first invalidate
1799 // message that signals a refresh as the beginning of the
1800 // frame. Otherwise the real frame time will be
1801 // underestimated.
1802 mFrameStartTime = frameStart;
1803 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001804 signalRefresh();
1805 }
1806 break;
1807 }
1808 case MessageQueue::REFRESH: {
1809 handleMessageRefresh();
1810 break;
1811 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001812 }
1813}
1814
Dan Stoza6b9454d2014-11-07 16:00:59 -08001815bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001816 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001817 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001818
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001819 bool flushedATransaction = flushTransactionQueues();
1820
1821 bool runHandleTransaction = transactionFlags &&
1822 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1823
1824 if (runHandleTransaction) {
1825 handleTransaction(eTransactionMask);
1826 } else {
1827 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001828 }
1829
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001830 if (transactionFlushNeeded()) {
1831 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001832 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001833
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001834 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835}
1836
Mathias Agopian4fec8732012-06-29 14:12:52 -07001837void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001838 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001839
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001840 mRefreshPending = false;
1841
Lloyd Piqueab039b52019-02-13 14:22:42 -08001842 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001843 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001844 for (const auto& [_, display] : mDisplays) {
1845 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1846 }
1847 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1848 auto compositionLayer = layer->getCompositionLayer();
1849 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1850 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001851 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1852 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1853 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001854 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001855 }
1856
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001857 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001858 refreshArgs.outputColorSetting = useColorManagement
1859 ? mDisplayColorSetting
1860 : compositionengine::OutputColorSetting::kUnmanaged;
1861 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1862 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001863
1864 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1865 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001866
1867 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1868 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1869 mDrawingState.colorMatrixChanged = false;
1870 }
1871
1872 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1873
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001874 if (mDebugRegion != 0) {
1875 refreshArgs.devOptFlashDirtyRegionsDelay =
1876 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1877 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001878
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001879 mGeometryInvalid = false;
1880
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001881 // Store the present time just before calling to the composition engine so we could notify
1882 // the scheduler.
1883 const auto presentTime = systemTime();
1884
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001885 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001886 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1887 // Reset the frame start time now that we've recorded this frame.
1888 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001889
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001890 mScheduler->onDisplayRefreshed(presentTime);
1891
David Sodmanfa9b2af2017-12-24 13:28:59 -08001892 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001893 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001894
Lloyd Pique66d68602019-02-13 14:23:31 -08001895 mHadClientComposition =
1896 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1897 auto& displayDevice = tokenDisplayPair.second;
1898 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1899 });
1900 mHadDeviceComposition =
1901 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1902 auto& displayDevice = tokenDisplayPair.second;
1903 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1904 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001905
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001906 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001907
David Sodman7e4ae112018-02-09 15:02:28 -08001908 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001909 if (mVisibleRegionsDirty) {
1910 mVisibleRegionsDirty = false;
1911 if (mTracingEnabled) {
1912 mTracing.notify("visibleRegionsDirty");
1913 }
1914 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001915
1916 if (mCompositionEngine->needsAnotherUpdate()) {
1917 signalLayerUpdate();
1918 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001919}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001920
David Sodmanfa9b2af2017-12-24 13:28:59 -08001921
1922bool SurfaceFlinger::handleMessageInvalidate() {
1923 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001924 bool refreshNeeded = handlePageFlip();
1925
Vishnu Nair4351ad52019-02-11 14:13:02 -08001926 if (mVisibleRegionsDirty) {
1927 computeLayerBounds();
1928 }
1929
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001930 for (auto& layer : mLayersPendingRefresh) {
1931 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001932 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001933 invalidateLayerStack(layer, visibleReg);
1934 }
1935 mLayersPendingRefresh.clear();
1936 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001937}
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1940 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Update queue of past composite+present times and determine the
1942 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001945 while (!getBE().mCompositePresentTimes.empty()) {
1946 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Cached values should have been updated before calling this method,
1948 // which helps avoid duplicate syscalls.
1949 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1950 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1951 break;
1952 }
1953 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
1957 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001958 while (getBE().mCompositePresentTimes.size() > 16) {
1959 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 }
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001963}
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1966 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 // Integer division and modulo round toward 0 not -inf, so we need to
1968 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1970 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1971 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972
Ana Krulec757f63a2019-01-25 10:46:18 -08001973 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001974 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001975 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001976 }
1977
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Snap the latency to a value that removes scheduling jitter from the
1979 // composition and present times, which often have >1ms of jitter.
1980 // Reducing jitter is important if an app attempts to extrapolate
1981 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001982 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001984 nsecs_t bias = stats.vsyncPeriod / 2;
1985 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1986 nsecs_t snappedCompositeToPresentLatency =
1987 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988
David Sodman99974d22017-11-28 12:04:33 -08001989 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001990 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1991 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001992 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993}
1994
David Sodman2b406362017-12-15 13:33:47 -08001995void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001996{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 ATRACE_CALL();
1998 ALOGV("postComposition");
1999
Brian Anderson3546a3f2016-07-14 11:51:14 -07002000 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002001 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002002 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002003 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002004 }
2005
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002006 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002007 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008
David Sodman73beded2017-11-15 11:56:06 -08002009 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002010 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002011 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002013 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2014 ->getRenderSurface()
2015 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002016 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017 } else {
2018 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2019 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020
David Sodman73beded2017-11-15 11:56:06 -08002021 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002022 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2023 mPreviousPresentFences[0] = displayDevice
2024 ? getHwComposer().getPresentFence(*displayDevice->getId())
2025 : Fence::NO_FENCE;
2026 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028
Ana Krulece588e312018-09-18 12:32:24 -07002029 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002030 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031
Lloyd Piqueab039b52019-02-13 14:22:42 -08002032 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2033 // be sampled a little later than when we started doing work for this frame,
2034 // but that should be okay since updateCompositorTiming has snapping logic.
2035 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2036 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002037 CompositorTiming compositorTiming;
2038 {
David Sodman99974d22017-11-28 12:04:33 -08002039 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2040 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002041 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042
Robert Carr2047fae2016-11-28 14:09:09 -08002043 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002044 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2045 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002046 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002047 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002048 }
Robert Carr2047fae2016-11-28 14:09:09 -08002049 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002050
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002051 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002052 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002053 }
2054
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002055 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002056 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2057 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002058 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002059 }
2060 }
2061
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002062 if (mAnimCompositionPending) {
2063 mAnimCompositionPending = false;
2064
Brian Anderson4e606e32017-03-16 15:34:57 -07002065 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002067 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002068 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002069 // The HWC doesn't support present fences, so use the refresh
2070 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002071 const nsecs_t presentTime =
2072 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002073 mAnimFrameTracker.setActualPresentTime(presentTime);
2074 }
2075 mAnimFrameTracker.advanceFrame();
2076 }
Dan Stozab90cf072015-03-05 11:05:59 -08002077
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002078 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002079 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002080 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002081 }
2082
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002083 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002084
Lloyd Pique32cbe282018-10-19 13:09:22 -07002085 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2086 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002087 return;
2088 }
2089
2090 nsecs_t currentTime = systemTime();
2091 if (mHasPoweredOff) {
2092 mHasPoweredOff = false;
2093 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002094 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002095 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002096 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2097 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002098 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002099 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002100 }
David Sodman4a36e932017-11-07 14:29:47 -08002101 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002102 }
David Sodman4a36e932017-11-07 14:29:47 -08002103 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002104
2105 {
2106 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002107 if (mTexturePool.size() < mTexturePoolSize) {
2108 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002109 const size_t offset = mTexturePool.size();
2110 mTexturePool.resize(mTexturePoolSize);
2111 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2112 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002113 } else if (mTexturePool.size() > mTexturePoolSize) {
2114 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2115 const size_t offset = mTexturePoolSize;
2116 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2117 mTexturePool.resize(mTexturePoolSize);
2118 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002119 }
2120 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002121
Ady Abrahambe0f9482019-04-24 15:41:53 -07002122 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002123 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002124
Kevin DuBois413287f2019-02-25 08:46:47 -08002125 if (mLumaSampling && mRegionSamplingThread) {
2126 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002127 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002128
2129 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2130 // side-effect of getTotalSize(), so we check that again here
2131 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002132 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002133 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2134 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135}
2136
Vishnu Nair4351ad52019-02-11 14:13:02 -08002137void SurfaceFlinger::computeLayerBounds() {
2138 for (const auto& pair : mDisplays) {
2139 const auto& displayDevice = pair.second;
2140 const auto display = displayDevice->getCompositionDisplay();
2141 for (const auto& layer : mDrawingState.layersSortedByZ) {
2142 // only consider the layers on the given layer stack
2143 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002144 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002145 }
2146
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002147 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2148 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149 }
2150 }
2151}
2152
David Sodmanfa9b2af2017-12-24 13:28:59 -08002153void SurfaceFlinger::postFrame()
2154{
2155 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002156 const auto display = getDefaultDisplayDeviceLocked();
2157 if (display && getHwComposer().isConnected(*display->getId())) {
2158 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2160 logFrameStats();
2161 }
2162 }
2163}
2164
Mathias Agopian87baae12012-07-31 12:38:26 -07002165void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166{
Mathias Agopian841cde52012-03-01 15:44:37 -08002167 ATRACE_CALL();
2168
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002169 // here we keep a copy of the drawing state (that is the state that's
2170 // going to be overwritten by handleTransactionLocked()) outside of
2171 // mStateLock so that the side-effects of the State assignment
2172 // don't happen with mStateLock held (which can cause deadlocks).
2173 State drawingState(mDrawingState);
2174
Mathias Agopianca4d3602011-05-19 15:38:14 -07002175 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002176 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177
Mathias Agopianca4d3602011-05-19 15:38:14 -07002178 // Here we're guaranteed that some transaction flags are set
2179 // so we can call handleTransactionLocked() unconditionally.
2180 // We call getTransactionFlags(), which will also clear the flags,
2181 // with mStateLock held to guarantee that mCurrentState won't change
2182 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002183
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002184 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002185 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002186 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002187
Mathias Agopianca4d3602011-05-19 15:38:14 -07002188 mDebugInTransaction = 0;
2189 invalidateHwcGeometry();
2190 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002191}
2192
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2194 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002195 const std::optional<DisplayIdentificationInfo> info =
2196 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002197
Dominik Laskowski075d3172018-05-24 15:50:06 -07002198 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002199 continue;
2200 }
2201
Lloyd Piqueba04e622017-12-14 17:11:26 -08002202 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002203 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002204 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002205 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2206 initScheduler(info->id);
2207 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002208 mPhysicalDisplayTokens[info->id] = new BBinder();
2209 DisplayDeviceState state;
2210 state.displayId = info->id;
2211 state.isSecure = true; // All physical displays are currently considered secure.
2212 state.displayName = info->name;
2213 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2214 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002215 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002217 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002218
Dominik Laskowski075d3172018-05-24 15:50:06 -07002219 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2220 if (index >= 0) {
2221 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2222 mInterceptor->saveDisplayDeletion(state.sequenceId);
2223 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002224 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002225 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002226 }
2227
2228 processDisplayChangesLocked();
2229 }
2230
2231 mPendingHotplugEvents.clear();
2232}
2233
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002234void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002235 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2236 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002237}
2238
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002240 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002241 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 const sp<IGraphicBufferProducer>& producer) {
2243 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002244 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002246 creationArgs.isSecure = state.isSecure;
2247 creationArgs.displaySurface = dispSurface;
2248 creationArgs.hasWideColorGamut = false;
2249 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002250 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002251
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002252 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002253 creationArgs.isPrimary = isInternalDisplay;
2254
2255 if (useColorManagement && displayId) {
2256 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002257 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002258 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002259 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002261
Dominik Laskowski7e045462018-05-30 13:02:02 -07002262 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002263 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002264 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265 }
tangrobin6753a022018-08-10 10:58:54 +08002266 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267
Dominik Laskowski075d3172018-05-24 15:50:06 -07002268 if (displayId) {
2269 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002270 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002272 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273
Lloyd Pique90c115d2018-09-18 21:39:42 -07002274 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002276 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 // Make sure that composition can never be stalled by a virtual display
2279 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002280 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002281 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2283 }
2284
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 creationArgs.displayInstallOrientation =
2286 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002287
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002289 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290
Lloyd Pique90c115d2018-09-18 21:39:42 -07002291 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292
2293 if (maxFrameBufferAcquiredBuffers >= 3) {
2294 nativeWindowSurface->preallocateBuffers();
2295 }
2296
2297 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002299 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002301 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002303 display->getCompositionDisplay()->setColorProfile(
2304 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2305 RenderIntent::COLORIMETRIC,
2306 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002307 if (!state.isVirtual()) {
2308 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002309 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2310 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002311 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002312
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 display->setLayerStack(state.layerStack);
2314 display->setProjection(state.orientation, state.viewport, state.frame);
2315 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318}
2319
Lloyd Pique347200f2017-12-14 17:00:15 -08002320void SurfaceFlinger::processDisplayChangesLocked() {
2321 // here we take advantage of Vector's copy-on-write semantics to
2322 // improve performance by skipping the transaction entirely when
2323 // know that the lists are identical
2324 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2325 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2326 if (!curr.isIdenticalTo(draw)) {
2327 mVisibleRegionsDirty = true;
2328 const size_t cc = curr.size();
2329 size_t dc = draw.size();
2330
2331 // find the displays that were removed
2332 // (ie: in drawing state but not in current state)
2333 // also handle displays that changed
2334 // (ie: displays that are in both lists)
2335 for (size_t i = 0; i < dc;) {
2336 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2337 if (j < 0) {
2338 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002340 // Save display ID before disconnecting.
2341 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002342 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002343
2344 if (!display->isVirtual()) {
2345 LOG_ALWAYS_FATAL_IF(!displayId);
2346 dispatchDisplayHotplugEvent(displayId->value, false);
2347 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002349
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002350 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 } else {
2352 // this display is in both lists. see if something changed.
2353 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002355 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2356 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2357 if (state_binder != draw_binder) {
2358 // changing the surface is like destroying and
2359 // recreating the DisplayDevice, so we just remove it
2360 // from the drawing state, so that it get re-added
2361 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002363 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002365 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002366 mDrawingState.displays.removeItemsAt(i);
2367 dc--;
2368 // at this point we must loop to the next item
2369 continue;
2370 }
2371
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002373 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002375 }
2376 if ((state.orientation != draw[i].orientation) ||
2377 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 }
2380 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002382 }
2383 }
2384 }
2385 ++i;
2386 }
2387
2388 // find displays that were added
2389 // (ie: in current state but not in drawing state)
2390 for (size_t i = 0; i < cc; i++) {
2391 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2392 const DisplayDeviceState& state(curr[i]);
2393
Lloyd Pique542307f2018-10-19 13:24:08 -07002394 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002395 sp<IGraphicBufferProducer> producer;
2396 sp<IGraphicBufferProducer> bqProducer;
2397 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002398 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002399
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002401 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 // Virtual displays without a surface are dormant:
2403 // they have external state (layer stack, projection,
2404 // etc.) but no internal state (i.e. a DisplayDevice).
2405 if (state.surface != nullptr) {
2406 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 int width = 0;
2409 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2410 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2411 int height = 0;
2412 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2413 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2414 int intFormat = 0;
2415 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2416 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002417 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002418
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 displayId =
2420 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 }
2422
2423 // TODO: Plumb requested format back up to consumer
2424
2425 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002427 bqProducer, bqConsumer,
2428 state.displayName);
2429
2430 dispSurface = vds;
2431 producer = vds;
2432 }
2433 } else {
2434 ALOGE_IF(state.surface != nullptr,
2435 "adding a supported display, but rendering "
2436 "surface is provided (%p), ignoring it",
2437 state.surface.get());
2438
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 displayId = state.displayId;
2440 LOG_ALWAYS_FATAL_IF(!displayId);
2441 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 producer = bqProducer;
2443 }
2444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002447 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002448 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002449 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002450 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002452 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 }
2454 }
2455 }
2456 }
2457 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002458
2459 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002460}
2461
Mathias Agopian87baae12012-07-31 12:38:26 -07002462void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002463{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002464 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2465
Dan Stoza7dde5992015-05-22 09:51:44 -07002466 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002467 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2468 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002469 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002470
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 /*
2472 * Traversal of the children
2473 * (perform the transaction for each of them if needed)
2474 */
2475
Marissa Wall06255332019-03-27 13:48:27 -07002476 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002477 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002479 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480
2481 const uint32_t flags = layer->doTransaction(0);
2482 if (flags & Layer::eVisibleRegion)
2483 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002484
2485 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002486 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002487 }
Robert Carr2047fae2016-11-28 14:09:09 -08002488 });
Marissa Wall06255332019-03-27 13:48:27 -07002489 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 }
2491
2492 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002493 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 */
2495
Mathias Agopiane57f2922012-08-09 16:29:12 -07002496 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002497 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002499 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002501 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002502 // The transform hint might have changed for some layers
2503 // (either because a display has changed, or because a layer
2504 // as changed).
2505 //
2506 // Walk through all the layers in currentLayers,
2507 // and update their transform hint.
2508 //
2509 // If a layer is visible only on a single display, then that
2510 // display is used to calculate the hint, otherwise we use the
2511 // default display.
2512 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002513 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002514 // the hint is set before we acquire a buffer from the surface texture.
2515 //
2516 // NOTE: layer transactions have taken place already, so we use their
2517 // drawing state. However, SurfaceFlinger's own transaction has not
2518 // happened yet, so we must use the current state layer list
2519 // (soon to become the drawing state list).
2520 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002521 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002522 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002523 bool first = true;
2524 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002525 // NOTE: we rely on the fact that layers are sorted by
2526 // layerStack first (so we don't have to traverse the list
2527 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002529 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002530 currentlayerStack = layerStack;
2531 // figure out if this layerstack is mirrored
2532 // (more than one display) if so, pick the default display,
2533 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002534 hintDisplay = nullptr;
2535 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002536 if (display->getCompositionDisplay()
2537 ->belongsInOutput(layer->getLayerStack(),
2538 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002539 if (hintDisplay) {
2540 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002541 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002544 }
2545 }
2546 }
2547 }
Chet Haase91d25932013-04-11 15:24:55 -07002548
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002549 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002550 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2551 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002552
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002553 // could be null when this layer is using a layerStack
2554 // that is not visible on any display. Also can occur at
2555 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002556 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002557 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002558
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002559 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002560 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 if (hintDisplay) {
2562 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002563 }
Robert Carr2047fae2016-11-28 14:09:09 -08002564
2565 first = false;
2566 });
Mathias Agopian84300952012-11-21 16:02:13 -08002567 }
2568
2569
Mathias Agopian3559b072012-08-15 13:46:03 -07002570 /*
2571 * Perform our own transaction if needed
2572 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573
2574 if (mLayersAdded) {
2575 mLayersAdded = false;
2576 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002577 mVisibleRegionsDirty = true;
2578 }
2579
2580 // some layers might have been removed, so
2581 // we need to update the regions they're exposing.
2582 if (mLayersRemoved) {
2583 mLayersRemoved = false;
2584 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002585 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002589 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002590 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002591 }
Robert Carr2047fae2016-11-28 14:09:09 -08002592 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 }
2594
Vishnu Nairec0ab382019-02-13 15:32:56 -08002595 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002597}
2598
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002599void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002600 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002601 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002602 return;
2603 }
2604
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002605 if (mVisibleRegionsDirty || mInputInfoChanged) {
2606 mInputInfoChanged = false;
2607 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002608 } else if (mInputWindowCommands.syncInputWindows) {
2609 // If the caller requested to sync input windows, but there are no
2610 // changes to input windows, notify immediately.
2611 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002612 }
2613
Arthur Hung6cbb9752019-09-05 16:38:18 +08002614 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002615}
2616
2617void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002618 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002619
2620 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2621 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002622 // When calculating the screen bounds we ignore the transparent region since it may
2623 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002624 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002625 }
2626 });
chaviw291d88a2019-02-14 10:33:58 -08002627
2628 mInputFlinger->setInputWindows(inputHandles,
2629 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2630 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002631}
2632
Vishnu Nairec0ab382019-02-13 15:32:56 -08002633void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002634 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002635 mPendingInputWindowCommands.clear();
2636}
2637
Riley Andrews03414a12014-07-01 14:22:59 -07002638void SurfaceFlinger::updateCursorAsync()
2639{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002640 compositionengine::CompositionRefreshArgs refreshArgs;
2641 for (const auto& [_, display] : mDisplays) {
2642 if (display->getId()) {
2643 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002644 }
2645 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002646
2647 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648}
2649
Ady Abraham2139f732019-11-13 18:56:40 -08002650void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2651 Scheduler::ConfigEvent event) {
2652 Mutex::Autolock lock(mStateLock);
2653 changeRefreshRateLocked(refreshRate, event);
2654}
2655
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002656void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2657 if (mScheduler) {
2658 // In practice it's not allowed to hotplug in/out the primary display once it's been
2659 // connected during startup, but some tests do it, so just warn and return.
2660 ALOGW("Can't re-init scheduler");
2661 return;
2662 }
2663
Ady Abraham2139f732019-11-13 18:56:40 -08002664 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002665 mRefreshRateConfigs =
2666 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2667 getHwComposer().getConfigs(
2668 primaryDisplayId),
2669 currentConfig);
2670 mRefreshRateStats =
2671 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2672 currentConfig, HWC_POWER_MODE_OFF);
2673 mRefreshRateStats->setConfigMode(currentConfig);
2674
2675 // start the EventThread
2676 mScheduler =
2677 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002678 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002679 mAppConnectionHandle =
2680 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2681 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2682 impl::EventThread::InterceptVSyncsCallback());
2683 mSfConnectionHandle =
2684 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2685 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2686 [this](nsecs_t timestamp) {
2687 mInterceptor->saveVSyncEvent(timestamp);
2688 });
2689
2690 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2691 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2692 mPhaseOffsets->getCurrentOffsets());
2693
2694 mRegionSamplingThread =
2695 new RegionSamplingThread(*this, *mScheduler,
2696 RegionSamplingThread::EnvironmentTimingTunables());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002697}
2698
Mathias Agopian4fec8732012-06-29 14:12:52 -07002699void SurfaceFlinger::commitTransaction()
2700{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002701 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002702
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002703 mTransactionPending = false;
2704 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706}
2707
Lloyd Pique58e24a32019-08-01 15:50:14 -07002708void SurfaceFlinger::commitTransactionLocked() {
2709 if (!mLayersPendingRemoval.isEmpty()) {
2710 // Notify removed layers now that they can't be drawn from
2711 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002712 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002713
2714 // Ensure any buffers set to display on any children are released.
2715 if (l->isRemovedFromCurrentState()) {
2716 l->latchAndReleaseBuffer();
2717 }
2718
2719 // If the layer has been removed and has no parent, then it will not be reachable
2720 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2721 // ensure we can copy its current to drawing state.
2722 if (!l->getParent()) {
2723 mOffscreenLayers.emplace(l.get());
2724 }
2725 }
2726 mLayersPendingRemoval.clear();
2727 }
2728
2729 // If this transaction is part of a window animation then the next frame
2730 // we composite should be considered an animation as well.
2731 mAnimCompositionPending = mAnimTransactionPending;
2732
2733 mDrawingState = mCurrentState;
2734 // clear the "changed" flags in current state
2735 mCurrentState.colorMatrixChanged = false;
2736
2737 mDrawingState.traverseInZOrder([&](Layer* layer) {
2738 layer->commitChildList();
2739
2740 // If the layer can be reached when traversing mDrawingState, then the layer is no
2741 // longer offscreen. Remove the layer from the offscreenLayer set.
2742 if (mOffscreenLayers.count(layer)) {
2743 mOffscreenLayers.erase(layer);
2744 }
2745 });
2746
2747 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002748 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002749}
2750
Nataniel Borges2b796da2019-02-15 13:32:18 -08002751void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2752 if (mTracingEnabledChanged) {
2753 mTracingEnabled = mTracing.isEnabled();
2754 mTracingEnabledChanged = false;
2755 }
2756
2757 // Synchronize with Tracing thread
2758 std::unique_lock<std::mutex> lock;
2759 if (mTracingEnabled) {
2760 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2761 }
2762
2763 lockedOperation();
2764
2765 // Synchronize with Tracing thread
2766 if (mTracingEnabled) {
2767 lock.unlock();
2768 }
2769}
2770
chaviw74d90ad2019-04-26 14:45:26 -07002771void SurfaceFlinger::commitOffscreenLayers() {
2772 for (Layer* offscreenLayer : mOffscreenLayers) {
2773 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2774 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2775 if (!trFlags) return;
2776
2777 layer->doTransaction(0);
2778 layer->commitChildList();
2779 });
2780 }
2781}
2782
Chia-I Wuab0c3192017-08-01 11:29:00 -07002783void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002784 for (const auto& [token, displayDevice] : mDisplays) {
2785 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002786 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002787 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002788 }
2789 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002790}
2791
Dan Stoza6b9454d2014-11-07 16:00:59 -08002792bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793{
Ady Abraham09bd3922019-04-08 10:44:56 -07002794 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 ALOGV("handlePageFlip");
2796
Brian Andersond6927fb2016-07-23 23:37:30 -07002797 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002800 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002801 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002802
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002803 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2804
Eric Penner51c59cd2014-07-28 19:51:58 -07002805 // Store the set of layers that need updates. This set must not change as
2806 // buffers are being latched, as this could result in a deadlock.
2807 // Example: Two producers share the same command stream and:
2808 // 1.) Layer 0 is latched
2809 // 2.) Layer 0 gets a new frame
2810 // 2.) Layer 1 gets a new frame
2811 // 3.) Layer 1 is latched.
2812 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2813 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002815 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002817 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002818 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002819 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002820 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002821 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002822 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002823 } else {
2824 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 }
Robert Carr2047fae2016-11-28 14:09:09 -08002826 });
2827
chaviw49a108c2019-08-12 11:23:06 -07002828 // The client can continue submitting buffers for offscreen layers, but they will not
2829 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2830 // layers to ensure dequeueBuffer doesn't block indefinitely.
2831 for (Layer* offscreenLayer : mOffscreenLayers) {
2832 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2833 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2834 }
2835
Lloyd Piquef2c79392018-12-20 16:23:33 -08002836 if (!mLayersWithQueuedFrames.empty()) {
2837 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2838 // writes to Layer current state. See also b/119481871
2839 Mutex::Autolock lock(mStateLock);
2840
2841 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002842 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002843 mLayersPendingRefresh.push_back(layer);
2844 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002845 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002846 if (layer->isBufferLatched()) {
2847 newDataLatched = true;
2848 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002849 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002850 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002851
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002852 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002853
2854 // If we will need to wake up at some time in the future to deal with a
2855 // queued frame that shouldn't be displayed during this vsync period, wake
2856 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002857 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002858 signalLayerUpdate();
2859 }
2860
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002861 // enter boot animation on first buffer latch
2862 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2863 ALOGI("Enter boot animation");
2864 mBootStage = BootStage::BOOTANIMATION;
2865 }
2866
chaviw74b03172019-08-19 11:09:03 -07002867 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2868
Dan Stoza6b9454d2014-11-07 16:00:59 -08002869 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002870 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871}
2872
Mathias Agopianad456f92011-01-13 17:53:01 -08002873void SurfaceFlinger::invalidateHwcGeometry()
2874{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002876}
2877
Robert Carrc0df3122019-04-11 13:18:21 -07002878status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2879 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2880 const sp<IBinder>& parentHandle,
2881 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002882 // add this layer to the current state list
2883 {
2884 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002885 sp<Layer> parent;
2886 if (parentHandle != nullptr) {
2887 parent = fromHandle(parentHandle);
2888 if (parent == nullptr) {
2889 return NAME_NOT_FOUND;
2890 }
2891 } else {
2892 parent = parentLayer;
2893 }
2894
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002896 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002897 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002898 return NO_MEMORY;
2899 }
Robert Carrc0df3122019-04-11 13:18:21 -07002900
2901 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2902
Robert Carrb89ea9d2018-12-10 13:01:14 -08002903 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002905 } else if (parent == nullptr) {
2906 lbc->onRemovedFromCurrentState();
2907 } else if (parent->isRemovedFromCurrentState()) {
2908 parent->addChild(lbc);
2909 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002910 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911 parent->addChild(lbc);
2912 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002913
Yiwei Zhang243b3782018-05-15 17:40:04 -07002914 if (gbc != nullptr) {
2915 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2916 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2917 mMaxGraphicBufferProducerListSize,
2918 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2919 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002920 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002921 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002922 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002923 }
2924
Mathias Agopian96f08192010-06-02 23:28:45 -07002925 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002926 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002927
Dan Stoza7d89d062015-04-30 13:29:25 -07002928 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002929}
2930
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002931uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002932 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002933}
2934
Mathias Agopian3f844832013-08-07 21:24:32 -07002935uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002936 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937}
2938
Mathias Agopian3f844832013-08-07 21:24:32 -07002939uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002940 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002941}
2942
2943uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002944 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002945 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002946 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002948 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 }
2950 return old;
2951}
2952
Marissa Wall713b63f2018-10-17 15:42:43 -07002953bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002954 // to prevent onHandleDestroyed from being called while the lock is held,
2955 // we must keep a copy of the transactions (specifically the composer
2956 // states) around outside the scope of the lock
2957 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002958 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002959 {
2960 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002961
Valerie Haufce31b82019-04-30 16:41:14 -07002962 auto it = mTransactionQueues.begin();
2963 while (it != mTransactionQueues.end()) {
2964 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002965
Valerie Haufce31b82019-04-30 16:41:14 -07002966 while (!transactionQueue.empty()) {
2967 const auto& transaction = transactionQueue.front();
2968 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002969 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002970 transaction.states)) {
2971 setTransactionFlags(eTransactionFlushNeeded);
2972 break;
2973 }
2974 transactions.push_back(transaction);
2975 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2976 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002977 transaction.buffer, transaction.postTime,
2978 transaction.privileged, transaction.hasListenerCallbacks,
2979 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002980 transactionQueue.pop();
2981 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002982 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002983
Valerie Haufce31b82019-04-30 16:41:14 -07002984 if (transactionQueue.empty()) {
2985 it = mTransactionQueues.erase(it);
2986 mTransactionCV.broadcast();
2987 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002988 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002989 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002990 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002991 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002992 return flushedATransaction;
2993}
2994
2995bool SurfaceFlinger::transactionFlushNeeded() {
2996 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002997}
2998
chaviwca27f252018-02-06 16:46:39 -08002999
Marissa Wall17b4e452018-12-26 16:32:34 -08003000bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003001 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003002 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003003 if (!useCachedExpectedPresentTime)
3004 populateExpectedPresentTime();
3005
3006 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003007 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3008 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3009 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3010 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3011 return false;
3012 }
3013
Marissa Wall713b63f2018-10-17 15:42:43 -07003014 for (const ComposerState& state : states) {
3015 const layer_state_t& s = state.state;
3016 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3017 continue;
3018 }
3019 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003020 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003021 }
3022 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003023 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003024}
3025
Valerie Hau9dab9732019-08-20 09:29:25 -07003026void SurfaceFlinger::setTransactionState(
3027 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3028 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3029 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3030 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003031 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003032
Valerie Haubc6ddb12019-03-08 11:10:15 -08003033 const int64_t postTime = systemTime();
3034
Robert Carr14167e02019-02-13 13:50:55 -08003035 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3036
Mathias Agopian698c0872011-06-28 19:09:31 -07003037 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038
Marissa Wall713b63f2018-10-17 15:42:43 -07003039 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003040 auto itr = mTransactionQueues.find(applyToken);
3041 // if this is an animation frame, wait until prior animation frame has
3042 // been applied by SF
3043 if (flags & eAnimation) {
3044 while (itr != mTransactionQueues.end()) {
3045 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3046 if (CC_UNLIKELY(err != NO_ERROR)) {
3047 ALOGW_IF(err == TIMED_OUT,
3048 "setTransactionState timed out "
3049 "waiting for animation frame to apply");
3050 break;
3051 }
3052 itr = mTransactionQueues.find(applyToken);
3053 }
3054 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003055
3056 // Expected present time is computed and cached on invalidate, so it may be stale.
3057 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3058 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003059 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003060 uncacheBuffer, postTime, privileged,
3061 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003062 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003063 return;
3064 }
3065
Valerie Haubc6ddb12019-03-08 11:10:15 -08003066 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003067 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3068 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003069}
3070
Valerie Hau9dab9732019-08-20 09:29:25 -07003071void SurfaceFlinger::applyTransactionState(
3072 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3073 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3074 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3075 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3076 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003077 uint32_t transactionFlags = 0;
3078
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003079 if (flags & eAnimation) {
3080 // For window updates that are part of an animation we must wait for
3081 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003082 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003083 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003084 if (CC_UNLIKELY(err != NO_ERROR)) {
3085 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003086 // caller after a few seconds.
3087 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3088 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003089 mAnimTransactionPending = false;
3090 break;
3091 }
3092 }
3093 }
3094
chaviwca27f252018-02-06 16:46:39 -08003095 for (const DisplayState& display : displays) {
3096 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003097 }
3098
Valerie Hau9dab9732019-08-20 09:29:25 -07003099 // start and end registration for listeners w/ no surface so they can get their callback. Note
3100 // that listeners with SurfaceControls will start registration during setClientStateLocked
3101 // below.
3102 for (const auto& listener : listenerCallbacks) {
3103 mTransactionCompletedThread.startRegistration(listener);
3104 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003105 }
3106
Valerie Hau9dab9732019-08-20 09:29:25 -07003107 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003108 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003109 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003110 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3111 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003112 }
3113
Valerie Hau9dab9732019-08-20 09:29:25 -07003114 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003115 mTransactionCompletedThread.endRegistration(listenerCallback);
3116 }
3117
Marissa Walle2ffb422018-10-12 11:33:52 -07003118 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003119 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003120 mTransactionCompletedThread.sendCallbacks();
3121 }
3122 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003123
chaviw273171b2018-12-26 11:46:30 -08003124 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3125
Marissa Wall947d34e2019-03-29 14:03:53 -07003126 if (uncacheBuffer.isValid()) {
3127 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003128 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003129 }
3130
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003131 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3132 // anyway. This can be used as a flush mechanism for previous async transactions.
3133 // Empty animation transaction can be used to simulate back-pressure, so also force a
3134 // transaction for empty animation transactions.
3135 if (transactionFlags == 0 &&
3136 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003137 transactionFlags = eTransactionNeeded;
3138 }
3139
Marissa Wall06255332019-03-27 13:48:27 -07003140 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3141 // so we don't have to wake up again next frame to preform an uneeded traversal.
3142 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3143 transactionFlags = transactionFlags & (~eTraversalNeeded);
3144 mTraversalNeededMainThread = true;
3145 }
3146
Mathias Agopian386aa982011-11-07 21:58:03 -08003147 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003148 if (mInterceptor->isEnabled()) {
3149 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003150 }
Irvel468051e2016-06-13 16:44:44 -07003151
Mathias Agopian386aa982011-11-07 21:58:03 -08003152 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003153 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3154 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003155 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003156
3157 // if this is a synchronous transaction, wait for it to take effect
3158 // before returning.
3159 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003161 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003162 if (flags & eAnimation) {
3163 mAnimTransactionPending = true;
3164 }
chaviw4fe36852019-04-15 16:25:49 -07003165 if (mPendingInputWindowCommands.syncInputWindows) {
3166 mPendingSyncInputWindows = true;
3167 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003168
3169 // applyTransactionState can be called by either the main SF thread or by
3170 // another process through setTransactionState. While a given process may wish
3171 // to wait on synchronous transactions, the main SF thread should never
3172 // be blocked. Therefore, we only wait if isMainThread is false.
3173 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003174 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3175 if (CC_UNLIKELY(err != NO_ERROR)) {
3176 // just in case something goes wrong in SF, return to the
3177 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003178 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3179 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003180 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003181 break;
3182 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003183 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 }
3185}
3186
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003187uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3188 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3189 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003190
Mathias Agopiane57f2922012-08-09 16:29:12 -07003191 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003192 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3193
3194 const uint32_t what = s.what;
3195 if (what & DisplayState::eSurfaceChanged) {
3196 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3197 state.surface = s.surface;
3198 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003199 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003200 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003201 if (what & DisplayState::eLayerStackChanged) {
3202 if (state.layerStack != s.layerStack) {
3203 state.layerStack = s.layerStack;
3204 flags |= eDisplayTransactionNeeded;
3205 }
3206 }
3207 if (what & DisplayState::eDisplayProjectionChanged) {
3208 if (state.orientation != s.orientation) {
3209 state.orientation = s.orientation;
3210 flags |= eDisplayTransactionNeeded;
3211 }
3212 if (state.frame != s.frame) {
3213 state.frame = s.frame;
3214 flags |= eDisplayTransactionNeeded;
3215 }
3216 if (state.viewport != s.viewport) {
3217 state.viewport = s.viewport;
3218 flags |= eDisplayTransactionNeeded;
3219 }
3220 }
3221 if (what & DisplayState::eDisplaySizeChanged) {
3222 if (state.width != s.width) {
3223 state.width = s.width;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 if (state.height != s.height) {
3227 state.height = s.height;
3228 flags |= eDisplayTransactionNeeded;
3229 }
3230 }
3231
Mathias Agopiane57f2922012-08-09 16:29:12 -07003232 return flags;
3233}
3234
Robert Carr14167e02019-02-13 13:50:55 -08003235bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003236 IPCThreadState* ipc = IPCThreadState::self();
3237 const int pid = ipc->getCallingPid();
3238 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003239 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003240 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003241 return false;
3242 }
3243 return true;
3244}
3245
Marissa Wall3dad52d2019-03-22 14:03:19 -07003246uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003247 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3248 bool privileged,
3249 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003250 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003251
Valerie Hau9dab9732019-08-20 09:29:25 -07003252 for (auto& listener : s.listeners) {
3253 // note that startRegistration will not re-register if the listener has
3254 // already be registered for a prior surface control
3255 mTransactionCompletedThread.startRegistration(listener);
3256 listenerCallbacks.insert(listener);
3257 }
3258
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003259 sp<Layer> layer = nullptr;
3260 if (s.surface) {
3261 layer = fromHandle(s.surface);
3262 } else {
3263 // The client may provide us a null handle. Treat it as if the layer was removed.
3264 ALOGW("Attempt to set client state with a null layer handle");
3265 }
chaviw8b3871a2017-11-01 17:41:01 -07003266 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003267 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003268 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003269 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003270 }
chaviw8b3871a2017-11-01 17:41:01 -07003271 return 0;
3272 }
3273
chaviw8b3871a2017-11-01 17:41:01 -07003274 uint32_t flags = 0;
3275
Garfield Tan8a3083e2018-12-03 13:21:07 -08003276 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003277
3278 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3279 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003280 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003281 layer->pushPendingState();
3282 }
3283
chaviw8b3871a2017-11-01 17:41:01 -07003284 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003285 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003286 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 }
chaviw8b3871a2017-11-01 17:41:01 -07003288 }
3289 if (what & layer_state_t::eLayerChanged) {
3290 // NOTE: index needs to be calculated before we update the state
3291 const auto& p = layer->getParent();
3292 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003293 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003294 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 mCurrentState.layersSortedByZ.removeAt(idx);
3296 mCurrentState.layersSortedByZ.add(layer);
3297 // we need traversal (state changed)
3298 // AND transaction (list changed)
3299 flags |= eTransactionNeeded|eTraversalNeeded;
3300 }
chaviw8b3871a2017-11-01 17:41:01 -07003301 } else {
3302 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003303 flags |= eTransactionNeeded|eTraversalNeeded;
3304 }
3305 }
chaviw8b3871a2017-11-01 17:41:01 -07003306 }
3307 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003308 // NOTE: index needs to be calculated before we update the state
3309 const auto& p = layer->getParent();
3310 if (p == nullptr) {
3311 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3312 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3313 mCurrentState.layersSortedByZ.removeAt(idx);
3314 mCurrentState.layersSortedByZ.add(layer);
3315 // we need traversal (state changed)
3316 // AND transaction (list changed)
3317 flags |= eTransactionNeeded|eTraversalNeeded;
3318 }
3319 } else {
3320 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3321 flags |= eTransactionNeeded|eTraversalNeeded;
3322 }
chaviw8b3871a2017-11-01 17:41:01 -07003323 }
3324 }
3325 if (what & layer_state_t::eSizeChanged) {
3326 if (layer->setSize(s.w, s.h)) {
3327 flags |= eTraversalNeeded;
3328 }
3329 }
3330 if (what & layer_state_t::eAlphaChanged) {
3331 if (layer->setAlpha(s.alpha))
3332 flags |= eTraversalNeeded;
3333 }
3334 if (what & layer_state_t::eColorChanged) {
3335 if (layer->setColor(s.color))
3336 flags |= eTraversalNeeded;
3337 }
Peiyong Lind3788632018-09-18 16:01:31 -07003338 if (what & layer_state_t::eColorTransformChanged) {
3339 if (layer->setColorTransform(s.colorTransform)) {
3340 flags |= eTraversalNeeded;
3341 }
3342 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003343 if (what & layer_state_t::eBackgroundColorChanged) {
3344 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3345 flags |= eTraversalNeeded;
3346 }
3347 }
chaviw8b3871a2017-11-01 17:41:01 -07003348 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003349 // TODO: b/109894387
3350 //
3351 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3352 // rotation. To see the problem observe that if we have a square parent, and a child
3353 // of the same size, then we rotate the child 45 degrees around it's center, the child
3354 // must now be cropped to a non rectangular 8 sided region.
3355 //
3356 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3357 // private API, and the WindowManager only uses rotation in one case, which is on a top
3358 // level layer in which cropping is not an issue.
3359 //
3360 // However given that abuse of rotation matrices could lead to surfaces extending outside
3361 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3362 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3363 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003364 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eTransparentRegionChanged) {
3368 if (layer->setTransparentRegionHint(s.transparentRegion))
3369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eFlagsChanged) {
3372 if (layer->setFlags(s.flags, s.mask))
3373 flags |= eTraversalNeeded;
3374 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003375 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003376 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003377 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003378 if (what & layer_state_t::eCornerRadiusChanged) {
3379 if (layer->setCornerRadius(s.cornerRadius))
3380 flags |= eTraversalNeeded;
3381 }
chaviw8b3871a2017-11-01 17:41:01 -07003382 if (what & layer_state_t::eLayerStackChanged) {
3383 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3384 // We only allow setting layer stacks for top level layers,
3385 // everything else inherits layer stack from its parent.
3386 if (layer->hasParent()) {
3387 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003388 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003389 } else if (idx < 0) {
3390 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003391 "that also does not appear in the top level layer list. Something"
3392 " has gone wrong.",
3393 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003394 } else if (layer->setLayerStack(s.layerStack)) {
3395 mCurrentState.layersSortedByZ.removeAt(idx);
3396 mCurrentState.layersSortedByZ.add(layer);
3397 // we need traversal (state changed)
3398 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003399 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003400 }
3401 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003402 if (what & layer_state_t::eDeferTransaction_legacy) {
3403 if (s.barrierHandle_legacy != nullptr) {
3404 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3405 } else if (s.barrierGbp_legacy != nullptr) {
3406 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003407 if (authenticateSurfaceTextureLocked(gbp)) {
3408 const auto& otherLayer =
3409 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003410 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003411 } else {
3412 ALOGE("Attempt to defer transaction to to an"
3413 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003414 }
3415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 // We don't trigger a traversal here because if no other state is
3417 // changed, we don't want this to cause any more work
3418 }
chaviw8b3871a2017-11-01 17:41:01 -07003419 if (what & layer_state_t::eReparentChildren) {
3420 if (layer->reparentChildren(s.reparentHandle)) {
3421 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003422 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003423 }
chaviw8b3871a2017-11-01 17:41:01 -07003424 if (what & layer_state_t::eDetachChildren) {
3425 layer->detachChildren();
3426 }
3427 if (what & layer_state_t::eOverrideScalingModeChanged) {
3428 layer->setOverrideScalingMode(s.overrideScalingMode);
3429 // We don't trigger a traversal here because if no other state is
3430 // changed, we don't want this to cause any more work
3431 }
Marissa Wall61c58622018-07-18 10:12:20 -07003432 if (what & layer_state_t::eTransformChanged) {
3433 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3436 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3437 flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eCropChanged) {
3440 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3441 }
Marissa Wall861616d2018-10-22 12:52:23 -07003442 if (what & layer_state_t::eFrameChanged) {
3443 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3444 }
Marissa Wall61c58622018-07-18 10:12:20 -07003445 if (what & layer_state_t::eAcquireFenceChanged) {
3446 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3447 }
3448 if (what & layer_state_t::eDataspaceChanged) {
3449 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3450 }
3451 if (what & layer_state_t::eHdrMetadataChanged) {
3452 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3453 }
3454 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3455 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eApiChanged) {
3458 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eSidebandStreamChanged) {
3461 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3462 }
Robert Carr720e5062018-07-30 17:45:14 -07003463 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003464 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003465 layer->setInputInfo(s.inputInfo);
3466 flags |= eTraversalNeeded;
3467 } else {
3468 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3469 }
Robert Carr720e5062018-07-30 17:45:14 -07003470 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003471 if (what & layer_state_t::eMetadataChanged) {
3472 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3473 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003474 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3475 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3476 flags |= eTraversalNeeded;
3477 }
3478 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003479 if (what & layer_state_t::eShadowRadiusChanged) {
3480 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3481 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003482 // This has to happen after we reparent children because when we reparent to null we remove
3483 // child layers from current state and remove its relative z. If the children are reparented in
3484 // the same transaction, then we have to make sure we reparent the children first so we do not
3485 // lose its relative z order.
3486 if (what & layer_state_t::eReparent) {
3487 bool hadParent = layer->hasParent();
3488 if (layer->reparent(s.parentHandleForChild)) {
3489 if (!hadParent) {
3490 mCurrentState.layersSortedByZ.remove(layer);
3491 }
3492 flags |= eTransactionNeeded | eTraversalNeeded;
3493 }
3494 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003495 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003496 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3497 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003498 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3499 }
3500 }
Marissa Wall78b72202019-03-15 14:58:34 -07003501 bool bufferChanged = what & layer_state_t::eBufferChanged;
3502 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3503 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003504 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003505 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003506 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3507 if (success) {
3508 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3509 success = ClientCache::getInstance()
3510 .registerErasedRecipient(s.cachedBuffer,
3511 wp<ClientCache::ErasedRecipient>(this));
3512 if (!success) {
3513 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3514 }
3515 }
Marissa Wall78b72202019-03-15 14:58:34 -07003516 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003517 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003518 } else if (bufferChanged) {
3519 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003520 }
Marissa Wall78b72202019-03-15 14:58:34 -07003521 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003522 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003523 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003524 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003525 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003526 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3527 // Do not put anything that updates layer state or modifies flags after
3528 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003529 return flags;
3530}
3531
chaviw273171b2018-12-26 11:46:30 -08003532uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3533 uint32_t flags = 0;
3534 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3535 flags |= eTraversalNeeded;
3536 }
3537
chaviwa911b102019-02-14 10:18:33 -08003538 if (inputWindowCommands.syncInputWindows) {
3539 flags |= eTraversalNeeded;
3540 }
3541
Vishnu Nairec0ab382019-02-13 15:32:56 -08003542 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003543 return flags;
3544}
3545
chaviwfe94a222019-08-21 13:52:59 -07003546status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3547 sp<IBinder>* outHandle) {
3548 if (!mirrorFromHandle) {
3549 return NAME_NOT_FOUND;
3550 }
3551
3552 sp<Layer> mirrorLayer;
3553 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003554 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003555
3556 {
3557 Mutex::Autolock _l(mStateLock);
3558 mirrorFrom = fromHandle(mirrorFromHandle);
3559 if (!mirrorFrom) {
3560 return NAME_NOT_FOUND;
3561 }
3562
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003563 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3564 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003565 if (result != NO_ERROR) {
3566 return result;
3567 }
3568
3569 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3570 }
3571
3572 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3573}
3574
Marissa Wall2d814fb2019-04-09 18:52:57 +00003575status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3576 uint32_t h, PixelFormat format, uint32_t flags,
3577 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003578 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003579 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3580 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003581 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003582 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003583 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003585 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003586
Robert Carrc0df3122019-04-11 13:18:21 -07003587 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3588 "Expected only one of parentLayer or parentHandle to be non-null. "
3589 "Programmer error?");
3590
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 status_t result = NO_ERROR;
3592
3593 sp<Layer> layer;
3594
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003595 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003596
Evan Roskya1f1e152019-01-24 16:17:46 -08003597 bool primaryDisplayOnly = false;
3598
3599 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3600 // TODO b/64227542
3601 if (metadata.has(METADATA_WINDOW_TYPE)) {
3602 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3603 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003604 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003605 primaryDisplayOnly = true;
3606 }
3607 }
3608
Mathias Agopian3165cc22012-08-08 19:42:09 -07003609 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003610 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003611 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3612 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003613
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003615 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003616 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003617 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003618 break;
chaviw13fdc492017-06-27 12:40:18 -07003619 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003620 // check if buffer size is set for color layer.
3621 if (w > 0 || h > 0) {
3622 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3623 int(w), int(h));
3624 return BAD_VALUE;
3625 }
3626
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003627 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3628 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003629 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003630 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003631 // check if buffer size is set for container layer.
3632 if (w > 0 || h > 0) {
3633 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3634 int(w), int(h));
3635 return BAD_VALUE;
3636 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003637 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3638 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003639 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 default:
3641 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 break;
3643 }
3644
Dan Stoza7d89d062015-04-30 13:29:25 -07003645 if (result != NO_ERROR) {
3646 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003648
Evan Roskya1f1e152019-01-24 16:17:46 -08003649 if (primaryDisplayOnly) {
3650 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003651 }
3652
Robert Carrb89ea9d2018-12-10 13:01:14 -08003653 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003654 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3655 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003656 if (result != NO_ERROR) {
3657 return result;
3658 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003659 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003660
3661 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003662 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663}
3664
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003665std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3666 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003667
3668 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003669 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003670
Dan Stoza436ccf32018-06-21 12:10:12 -07003671 // Grab the state lock since we're accessing mCurrentState
3672 Mutex::Autolock lock(mStateLock);
3673
Cody Northropbc755282017-03-31 12:00:08 -06003674 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003675 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003676 while (matchFound) {
3677 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003678 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003679 if (layer->getName() == uniqueName) {
3680 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003681 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003682 }
3683 });
3684 }
3685
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003686 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003687 return uniqueName;
3688}
3689
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003690status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003691 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003692 LayerMetadata metadata, PixelFormat& format,
3693 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003694 sp<IGraphicBufferProducer>* gbp,
3695 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003697 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698 case PIXEL_FORMAT_TRANSPARENT:
3699 case PIXEL_FORMAT_TRANSLUCENT:
3700 format = PIXEL_FORMAT_RGBA_8888;
3701 break;
3702 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003703 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 break;
3705 }
3706
chaviwb4c6e582019-08-16 14:35:07 -07003707 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003708 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003709 args.textureName = getNewTexture();
3710 {
3711 // Grab the SF state lock during this since it's the only safe way to access
3712 // RenderEngine when creating a BufferLayerConsumer
3713 // TODO: Check if this lock is still needed here
3714 Mutex::Autolock lock(mStateLock);
3715 layer = getFactory().createBufferQueueLayer(args);
3716 }
3717
Marissa Wallfd668622018-05-10 10:21:13 -07003718 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003720 *handle = layer->getHandle();
3721 *gbp = layer->getProducer();
3722 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003724
Marissa Wallfd668622018-05-10 10:21:13 -07003725 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727}
3728
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003729status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003730 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003731 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003732 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003733 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003734 args.displayDevice = getDefaultDisplayDevice();
3735 args.textureName = getNewTexture();
3736 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003737 if (outTransformHint) {
3738 *outTransformHint = layer->getTransformHint();
3739 }
Marissa Wall61c58622018-07-18 10:12:20 -07003740 *handle = layer->getHandle();
3741 *outLayer = layer;
3742
3743 return NO_ERROR;
3744}
3745
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003746status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003747 uint32_t h, uint32_t flags, LayerMetadata metadata,
3748 sp<IBinder>* handle, sp<Layer>* outLayer) {
3749 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003752 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003753}
3754
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003755status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003756 uint32_t w, uint32_t h, uint32_t flags,
3757 LayerMetadata metadata, sp<IBinder>* handle,
3758 sp<Layer>* outLayer) {
3759 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003760 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003761 *handle = (*outLayer)->getHandle();
3762 return NO_ERROR;
3763}
3764
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003765void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003766 mLayersPendingRemoval.add(layer);
3767 mLayersRemoved = true;
3768 setTransactionFlags(eTransactionNeeded);
3769}
3770
Robert Carr695d5282018-12-18 15:27:58 -08003771void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003772{
Robert Carr2e102c92018-10-23 12:11:15 -07003773 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003774 // If a layer has a parent, we allow it to out-live it's handle
3775 // with the idea that the parent holds a reference and will eventually
3776 // be cleaned up. However no one cleans up the top-level so we do so
3777 // here.
3778 if (layer->getParent() == nullptr) {
3779 mCurrentState.layersSortedByZ.remove(layer);
3780 }
3781 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003782
3783 auto it = mLayersByLocalBinderToken.begin();
3784 while (it != mLayersByLocalBinderToken.end()) {
3785 if (it->second == layer) {
3786 it = mLayersByLocalBinderToken.erase(it);
3787 } else {
3788 it++;
3789 }
3790 }
3791
Robert Carr695d5282018-12-18 15:27:58 -08003792 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003793}
3794
Mathias Agopianb60314a2012-04-10 22:09:54 -07003795// ---------------------------------------------------------------------------
3796
Andy McFadden13a082e2012-08-24 10:16:42 -07003797void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003798 const auto display = getDefaultDisplayDeviceLocked();
3799 if (!display) return;
3800
3801 const sp<IBinder> token = display->getDisplayToken().promote();
3802 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003803
Jesse Hall01e29052013-02-19 16:13:35 -08003804 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003805 Vector<ComposerState> state;
3806 Vector<DisplayState> displays;
3807 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003808 d.what = DisplayState::eDisplayProjectionChanged |
3809 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003810 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003811 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003812 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003813 d.frame.makeInvalid();
3814 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003815 d.width = 0;
3816 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003817 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003818 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3819 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003820
Dominik Laskowskie9774092018-12-11 10:04:24 -08003821 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003822
Dominik Laskowski83b88212018-12-11 13:34:06 -08003823 const nsecs_t vsyncPeriod = getVsyncPeriod();
3824 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003825
Brian Andersond0010582017-03-07 13:20:31 -08003826 // Use phase of 0 since phase is not known.
3827 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003828 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003829 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003830}
3831
3832void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003833 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003834 postMessageAsync(
3835 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003836}
3837
Ady Abraham27c70212019-06-11 10:52:26 -07003838void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3839 if (mHWCVsyncState != enabled) {
3840 getHwComposer().setVsyncEnabled(displayId, enabled);
3841 mHWCVsyncState = enabled;
3842 }
3843}
3844
Dominik Laskowskie9774092018-12-11 10:04:24 -08003845void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003846 if (display->isVirtual()) {
3847 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003848 return;
3849 }
3850
Dominik Laskowski075d3172018-05-24 15:50:06 -07003851 const auto displayId = display->getId();
3852 LOG_ALWAYS_FATAL_IF(!displayId);
3853
Dominik Laskowski34157762018-10-31 13:07:19 -07003854 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003855
3856 int currentMode = display->getPowerMode();
3857 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003858 return;
3859 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003861 display->setPowerMode(mode);
3862
Lloyd Pique4dccc412018-01-22 17:21:36 -08003863 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003864 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003865 }
3866
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003868 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003869 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003870 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003871 mScheduler->onScreenAcquired(mAppConnectionHandle);
3872 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003875 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003876 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003877 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003878
3879 struct sched_param param = {0};
3880 param.sched_priority = 1;
3881 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3882 ALOGW("Couldn't set SCHED_FIFO on display on");
3883 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003884 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003885 // Turn off the display
3886 struct sched_param param = {0};
3887 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3888 ALOGW("Couldn't set SCHED_OTHER on display off");
3889 }
3890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003891 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003892 mScheduler->disableHardwareVsync(true);
3893 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003894 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003895
Ady Abraham27c70212019-06-11 10:52:26 -07003896 // Make sure HWVsync is disabled before turning off the display
3897 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3898
Dominik Laskowski075d3172018-05-24 15:50:06 -07003899 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003900 mVisibleRegionsDirty = true;
3901 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003902 } else if (mode == HWC_POWER_MODE_DOZE ||
3903 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003904 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003905 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003907 mScheduler->onScreenAcquired(mAppConnectionHandle);
3908 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003909 }
3910 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3911 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003912 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003913 mScheduler->disableHardwareVsync(true);
3914 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003915 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003916 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003917 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003918 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003919 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003920 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003921
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003922 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003923 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003924 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003925 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003926 }
3927
Dominik Laskowski34157762018-10-31 13:07:19 -07003928 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929}
3930
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003931void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003932 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003933 const auto display = getDisplayDevice(displayToken);
3934 if (!display) {
3935 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3936 displayToken.get());
3937 } else if (display->isVirtual()) {
3938 ALOGW("Attempt to set power mode %d for virtual display", mode);
3939 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003940 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003941 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003942 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003943}
3944
3945// ---------------------------------------------------------------------------
3946
Dominik Laskowskic2867142019-01-21 11:33:38 -08003947status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3948 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003949 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003950
Mathias Agopianbd115332013-04-18 16:41:04 -07003951 IPCThreadState* ipc = IPCThreadState::self();
3952 const int pid = ipc->getCallingPid();
3953 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003954
Mathias Agopianbd115332013-04-18 16:41:04 -07003955 if ((uid != AID_SHELL) &&
3956 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003957 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3958 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003959 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003960 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003961 // (this would indicate SF is stuck, but we want to be able to
3962 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003963 status_t err = mStateLock.timedLock(s2ns(1));
3964 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003965 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003966 StringAppendF(&result,
3967 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3968 "(no locks held)\n",
3969 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003970 }
3971
Dominik Laskowskic2867142019-01-21 11:33:38 -08003972 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003973 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003974 {"--dispsync"s,
3975 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003976 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003977 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3978 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3979 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3980 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3981 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3982 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003983 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003984 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3985 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986
Dominik Laskowskic2867142019-01-21 11:33:38 -08003987 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988
Dominik Laskowski46470112019-08-02 13:13:11 -07003989 const auto it = dumpers.find(flag);
3990 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003991 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003992 } else if (!asProto) {
3993 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003994 }
3995
Mathias Agopian9795c422009-08-26 16:36:26 -07003996 if (locked) {
3997 mStateLock.unlock();
3998 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003999
Dominik Laskowski46470112019-08-02 13:13:11 -07004000 if (it == dumpers.end()) {
4001 const LayersProto layersProto = dumpProtoFromMainThread();
4002 if (asProto) {
4003 result.append(layersProto.SerializeAsString());
4004 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004005 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004006 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4007 result.append(LayerProtoParser::layerTreeToString(layerTree));
4008 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004009 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004010 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004013 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014 return NO_ERROR;
4015}
4016
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004017status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4018 if (asProto && mTracing.isEnabled()) {
4019 mTracing.writeToFileAsync();
4020 }
4021
4022 return doDump(fd, DumpArgs(), asProto);
4023}
4024
Dominik Laskowskic2867142019-01-21 11:33:38 -08004025void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004026 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004027 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028}
4029
Dominik Laskowskic2867142019-01-21 11:33:38 -08004030void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004031 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004032
Dominik Laskowskic2867142019-01-21 11:33:38 -08004033 if (args.size() > 1) {
4034 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004035 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004036 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004037 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004038 }
Robert Carr2047fae2016-11-28 14:09:09 -08004039 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004040 } else {
4041 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004042 }
4043}
4044
Dominik Laskowskic2867142019-01-21 11:33:38 -08004045void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004046 const bool clearAll = args.size() < 2;
4047 const auto name = clearAll ? String8() : String8(args[1]);
4048
Robert Carr2047fae2016-11-28 14:09:09 -08004049 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004050 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004051 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052 }
Robert Carr2047fae2016-11-28 14:09:09 -08004053 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004054
Svetoslavd85084b2014-03-20 10:28:31 -07004055 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056}
4057
Dominik Laskowskic2867142019-01-21 11:33:38 -08004058void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4059 mTimeStats->parseArgs(asProto, args, result);
4060}
4061
Jamie Gennis6547ff42013-07-16 20:12:42 -07004062// This should only be called from the main thread. Otherwise it would need
4063// the lock and should use mCurrentState rather than mDrawingState.
4064void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004065 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004066 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004067 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004068
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004069 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004070}
4071
Yiwei Zhang5434a782018-12-05 18:06:32 -08004072void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004073 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004074
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004075 if (isLayerTripleBufferingDisabled())
4076 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004077
Yiwei Zhang5434a782018-12-05 18:06:32 -08004078 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4079 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4080 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4081 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4082 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4083 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004084 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004085}
4086
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004087void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004088 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004089
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004090 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004091 result.append("\n");
4092
Ana Krulec757f63a2019-01-25 10:46:18 -08004093 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004094 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004095 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004096 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004097
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004098 HwcConfigIndexType defaultConfig;
4099 float minFps, maxFps;
4100 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004101 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004102 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004103 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004104 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004105 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4106 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004107
Ana Krulecc2870422019-01-29 19:00:58 -08004108 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004109}
4110
Yiwei Zhang5434a782018-12-05 18:06:32 -08004111void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4112 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004113 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4114 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004115 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004116 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004117 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004118 }
David Sodman4a36e932017-11-07 14:29:47 -08004119 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004120 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004121 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004122 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4123 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004124}
4125
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004126void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4127 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004128 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4129 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004130 for (const auto& segment : history) {
4131 if (!segment.usedThirdBuffer) {
4132 stats.twoBufferTime += segment.totalTime;
4133 }
4134 if (segment.occupancyAverage < 1.0f) {
4135 stats.doubleBufferedTime += segment.totalTime;
4136 } else if (segment.occupancyAverage < 2.0f) {
4137 stats.tripleBufferedTime += segment.totalTime;
4138 }
4139 ++stats.numSegments;
4140 stats.totalTime += segment.totalTime;
4141 }
4142}
4143
Yiwei Zhang5434a782018-12-05 18:06:32 -08004144void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4145 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004146
4147 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4148 const size_t count = currentLayers.size();
4149 for (size_t i=0 ; i<count ; i++) {
4150 currentLayers[i]->dumpFrameEvents(result);
4151 }
4152}
4153
Yiwei Zhang5434a782018-12-05 18:06:32 -08004154void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004155 result.append("Buffering stats:\n");
4156 result.append(" [Layer name] <Active time> <Two buffer> "
4157 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004158 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004159 typedef std::tuple<std::string, float, float, float> BufferTuple;
4160 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004161 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004162 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004163 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004164 if (stats.numSegments == 0) {
4165 continue;
4166 }
4167 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4168 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4169 stats.totalTime;
4170 float doubleBufferRatio = static_cast<float>(
4171 stats.doubleBufferedTime) / stats.totalTime;
4172 float tripleBufferRatio = static_cast<float>(
4173 stats.tripleBufferedTime) / stats.totalTime;
4174 sorted.insert({activeTime, {name, twoBufferRatio,
4175 doubleBufferRatio, tripleBufferRatio}});
4176 }
4177 for (const auto& sortedPair : sorted) {
4178 float activeTime = sortedPair.first;
4179 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004180 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4181 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004182 }
4183 result.append("\n");
4184}
4185
Yiwei Zhang5434a782018-12-05 18:06:32 -08004186void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004187 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004188 const auto displayId = display->getId();
4189 if (!displayId) {
4190 continue;
4191 }
4192 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004193 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004194 continue;
4195 }
4196
Yiwei Zhang5434a782018-12-05 18:06:32 -08004197 StringAppendF(&result,
4198 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4199 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004200 uint8_t port;
4201 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004202 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004203 result.append("no identification data\n");
4204 continue;
4205 }
4206
4207 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004208 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004209 continue;
4210 }
4211
4212 const auto edid = parseEdid(data);
4213 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004214 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004215 continue;
4216 }
4217
Yiwei Zhang5434a782018-12-05 18:06:32 -08004218 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219 result.append(edid->displayName.data(), edid->displayName.length());
4220 result.append("\"\n");
4221 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004222}
4223
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004224void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4225 std::string& result) const {
4226 hwc2_display_t hwcDisplayId;
4227 uint8_t port;
4228 DisplayIdentificationData data;
4229
4230 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4231 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4232 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4233 }
4234}
4235
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004237 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004238 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4239 StringAppendF(&result, "DisplayColorSetting: %s\n",
4240 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004241
4242 // TODO: print out if wide-color mode is active or not
4243
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004244 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004245 const auto displayId = display->getId();
4246 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004247 continue;
4248 }
4249
Yiwei Zhang5434a782018-12-05 18:06:32 -08004250 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004252 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004254 }
4255
Lloyd Pique32cbe282018-10-19 13:09:22 -07004256 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004257 StringAppendF(&result, " Current color mode: %s (%d)\n",
4258 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004259 }
4260 result.append("\n");
4261}
4262
Vishnu Nair8406fd72019-07-30 11:29:31 -07004263LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004264 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004265 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004266 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004267 layer->writeToProtoDrawingState(layerProto, traceFlags);
4268 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004269 });
4270
4271 return layersProto;
4272}
4273
Vishnu Nair0f085c62019-08-30 08:49:12 -07004274void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4275 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4276 // it.
4277 LayerProto* rootProto = layersProto.add_layers();
4278 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4279 rootProto->set_id(offscreenRootLayerId);
4280 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004281 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004282
4283 for (Layer* offscreenLayer : mOffscreenLayers) {
4284 // Add layer as child of the fake root
4285 rootProto->add_children(offscreenLayer->sequence);
4286
4287 // Add layer
4288 LayerProto* layerProto = layersProto.add_layers();
4289 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4290 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4291 traceFlags);
4292 layerProto->set_parent(offscreenRootLayerId);
4293
4294 // Add children
4295 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4296 if (layer == offscreenLayer) {
4297 return;
4298 }
4299 LayerProto* childProto = layersProto.add_layers();
4300 layer->writeToProtoDrawingState(childProto, traceFlags);
4301 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4302 });
4303 }
4304}
4305
Vishnu Nair8406fd72019-07-30 11:29:31 -07004306LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4307 LayersProto layersProto;
4308 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4309 return layersProto;
4310}
4311
Vishnu Nair0f085c62019-08-30 08:49:12 -07004312void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4313 result.append("Offscreen Layers:\n");
4314 postMessageSync(new LambdaMessage([&]() {
4315 for (Layer* offscreenLayer : mOffscreenLayers) {
4316 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4317 layer->dumpCallingUidPid(result);
4318 });
4319 }
4320 }));
4321}
4322
Dominik Laskowskic2867142019-01-21 11:33:38 -08004323void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4324 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 Colorizer colorizer(colorize);
4326
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327 // figure out if we're stuck somewhere
4328 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4331
4332 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004333 * Dump library configuration.
4334 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004335
4336 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004337 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004339 appendSfConfigString(result);
4340 appendUiConfigString(result);
4341 appendGuiConfigString(result);
4342 result.append("\n");
4343
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004344 result.append("\nDisplay identification data:\n");
4345 dumpDisplayIdentificationData(result);
4346
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004347 result.append("\nWide-Color information:\n");
4348 dumpWideColorInfo(result);
4349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004350 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004351 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004352 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004353 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004354 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004355
Andy McFadden41d67d72014-04-25 16:58:34 -07004356 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004357 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004358 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004359 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004360 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004361
Dan Stozab90cf072015-03-05 11:05:59 -08004362 dumpStaticScreenStats(result);
4363 result.append("\n");
4364
Alec Mouri40189b02019-03-05 15:07:54 -08004365 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4366 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4367 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004368
Dan Stozae77c7662016-05-13 11:37:28 -07004369 dumpBufferingStats(result);
4370
Andy McFadden4803b742012-09-24 19:07:20 -07004371 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372 * Dump the visible layer list
4373 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004374 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004375 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4377 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004378 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004379
Chia-I Wu2f884132018-09-13 15:17:58 -07004380 {
Lloyd Pique207def92019-02-28 16:09:52 -08004381 StringAppendF(&result, "Composition layers\n");
4382 mDrawingState.traverseInZOrder([&](Layer* layer) {
4383 auto compositionLayer = layer->getCompositionLayer();
4384 if (compositionLayer) compositionLayer->dump(result);
4385 });
4386 }
4387
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004389 * Dump Display state
4390 */
4391
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004392 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004394 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004395 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004396 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004397 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004398 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004399
4400 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004401 * Dump CompositionEngine state
4402 */
4403
4404 mCompositionEngine->dump(result);
4405
4406 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004407 * Dump SurfaceFlinger global state
4408 */
4409
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004410 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004411 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004412 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004413
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004414 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004416 DebugEGLImageTracker::getInstance()->dump(result);
4417
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004419 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4420 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004421 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4422 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004423 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424 StringAppendF(&result,
4425 " transaction-flags : %08x\n"
4426 " gpu_to_cpu_unsupported : %d\n",
4427 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004428
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004429 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004430 displayId && getHwComposer().isConnected(*displayId)) {
4431 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004432 StringAppendF(&result,
4433 " refresh-rate : %f fps\n"
4434 " x-dpi : %f\n"
4435 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004436 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4437 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004438 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441
Dan Stozae22aec72016-08-01 13:20:59 -07004442 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004443 * Tracing state
4444 */
4445 mTracing.dump(result);
4446 result.append("\n");
4447
4448 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004449 * HWC layer minidump
4450 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004451 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004452 const auto displayId = display->getId();
4453 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004454 continue;
4455 }
4456
Yiwei Zhang5434a782018-12-05 18:06:32 -08004457 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004458 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004459 const sp<DisplayDevice> displayDevice = display;
4460 mCurrentState.traverseInZOrder(
4461 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004462 result.append("\n");
4463 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464
4465 /*
4466 * Dump HWComposer state
4467 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004468 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004469 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004470 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004471 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004473 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004474
4475 /*
4476 * Dump gralloc state
4477 */
4478 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4479 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004480
4481 /*
4482 * Dump VrFlinger state if in use.
4483 */
4484 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4485 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004487 result.append("\n");
4488 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004489
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004490 result.append(mTimeStats->miniDump());
4491 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004492}
4493
Chia-I Wu28f320b2018-05-03 11:02:56 -07004494void SurfaceFlinger::updateColorMatrixLocked() {
4495 mat4 colorMatrix;
4496 if (mGlobalSaturationFactor != 1.0f) {
4497 // Rec.709 luma coefficients
4498 float3 luminance{0.213f, 0.715f, 0.072f};
4499 luminance *= 1.0f - mGlobalSaturationFactor;
4500 mat4 saturationMatrix = mat4(
4501 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4502 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4503 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4504 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4505 );
4506 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4507 } else {
4508 colorMatrix = mClientColorMatrix * mDaltonizer();
4509 }
4510
4511 if (mCurrentState.colorMatrix != colorMatrix) {
4512 mCurrentState.colorMatrix = colorMatrix;
4513 mCurrentState.colorMatrixChanged = true;
4514 setTransactionFlags(eTransactionNeeded);
4515 }
4516}
4517
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004518status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004519#pragma clang diagnostic push
4520#pragma clang diagnostic error "-Wswitch-enum"
4521 switch (static_cast<ISurfaceComposerTag>(code)) {
4522 // These methods should at minimum make sure that the client requested
4523 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004524 case BOOT_FINISHED:
4525 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004526 case CREATE_DISPLAY:
4527 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004528 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004529 case GET_ANIMATION_FRAME_STATS:
4530 case GET_HDR_CAPABILITIES:
4531 case SET_ACTIVE_CONFIG:
Ana Krulec0782b882019-10-15 17:34:54 -07004532 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004533 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004534 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004535 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4536 case SET_AUTO_LOW_LATENCY_MODE:
4537 case GET_GAME_CONTENT_TYPE_SUPPORT:
4538 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004539 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004540 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004541 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004542 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004543 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004544 case NOTIFY_POWER_HINT:
4545 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004546 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4547 IPCThreadState* ipc = IPCThreadState::self();
4548 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4549 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004550 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 }
Robert Carr1db73f62016-12-21 12:58:51 -08004552 return OK;
4553 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004554 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004555 IPCThreadState* ipc = IPCThreadState::self();
4556 const int pid = ipc->getCallingPid();
4557 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004558 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4559 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004560 return PERMISSION_DENIED;
4561 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004564 // Used by apps to hook Choreographer to SurfaceFlinger.
4565 case CREATE_DISPLAY_EVENT_CONNECTION:
4566 // The following calls are currently used by clients that do not
4567 // request necessary permissions. However, they do not expose any secret
4568 // information, so it is OK to pass them.
4569 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004570 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004571 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004572 case GET_PHYSICAL_DISPLAY_IDS:
4573 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004574 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004575 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004576 case GET_DISPLAY_CONFIGS:
4577 case GET_DISPLAY_STATS:
4578 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4579 // Calling setTransactionState is safe, because you need to have been
4580 // granted a reference to Client* and Handle* to do anything with it.
4581 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004582 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004583 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004584 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004585 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004586 case IS_WIDE_COLOR_DISPLAY:
4587 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4588 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004589 return OK;
4590 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004591 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004592 case CAPTURE_SCREEN:
4593 case ADD_REGION_SAMPLING_LISTENER:
4594 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004595 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004596 IPCThreadState* ipc = IPCThreadState::self();
4597 const int pid = ipc->getCallingPid();
4598 const int uid = ipc->getCallingUid();
4599 if ((uid != AID_GRAPHICS) &&
4600 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4601 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4602 return PERMISSION_DENIED;
4603 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004604 return OK;
4605 }
4606 // The following codes are deprecated and should never be allowed to access SF.
4607 case CONNECT_DISPLAY_UNUSED:
4608 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4609 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4610 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004611 }
chaviw93df2ea2019-04-30 16:45:12 -07004612 case CAPTURE_SCREEN_BY_ID: {
4613 IPCThreadState* ipc = IPCThreadState::self();
4614 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004615 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004616 return OK;
4617 }
4618 return PERMISSION_DENIED;
4619 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004621
4622 // These codes are used for the IBinder protocol to either interrogate the recipient
4623 // side of the transaction for its canonical interface descriptor or to dump its state.
4624 // We let them pass by default.
4625 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4626 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4627 code == IBinder::SYSPROPS_TRANSACTION) {
4628 return OK;
4629 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004630 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004631 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004632 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004633 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4634 return OK;
4635 }
4636 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4637 return PERMISSION_DENIED;
4638#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004639}
4640
Ana Krulec13be8ad2018-08-21 02:43:56 +00004641status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4642 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004643 status_t credentialCheck = CheckTransactCodeCredentials(code);
4644 if (credentialCheck != OK) {
4645 return credentialCheck;
4646 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004648 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4649 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004650 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004651 IPCThreadState* ipc = IPCThreadState::self();
4652 const int uid = ipc->getCallingUid();
4653 if (CC_UNLIKELY(uid != AID_SYSTEM
4654 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004655 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004656 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004657 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 return PERMISSION_DENIED;
4659 }
4660 int n;
4661 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004662 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004663 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004664 return NO_ERROR;
4665 case 1002: // SHOW_UPDATES
4666 n = data.readInt32();
4667 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004668 invalidateHwcGeometry();
4669 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004670 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004672 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004673 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004675 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004676 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004677 setTransactionFlags(
4678 eTransactionNeeded|
4679 eDisplayTransactionNeeded|
4680 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004681 return NO_ERROR;
4682 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004683 case 1006:{ // send empty update
4684 signalRefresh();
4685 return NO_ERROR;
4686 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004687 case 1008: // toggle use of hw composer
4688 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004689 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004690 invalidateHwcGeometry();
4691 repaintEverything();
4692 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004693 case 1009: // toggle use of transform hint
4694 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004695 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004696 invalidateHwcGeometry();
4697 repaintEverything();
4698 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004700 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004701 reply->writeInt32(0);
4702 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004703 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004704 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 return NO_ERROR;
4706 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004707 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004708 if (!display) {
4709 return NAME_NOT_FOUND;
4710 }
4711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004712 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004713 return NO_ERROR;
4714 }
4715 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004716 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004717 // daltonize
4718 n = data.readInt32();
4719 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004720 case 1:
4721 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4722 break;
4723 case 2:
4724 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4725 break;
4726 case 3:
4727 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4728 break;
4729 default:
4730 mDaltonizer.setType(ColorBlindnessType::None);
4731 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004732 }
4733 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004734 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004735 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004736 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004737 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004738
4739 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004740 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004741 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004742 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004743 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004744 // apply a color matrix
4745 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004746 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004747 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004748 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004749 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004750 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004751 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004752 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004754 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004755 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004756
4757 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4758 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004759 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004760 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4761 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4762 }
4763
Chia-I Wu28f320b2018-05-03 11:02:56 -07004764 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004765 return NO_ERROR;
4766 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004767 case 1016: { // Unused.
4768 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004769 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004770 case 1017: {
4771 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004772 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004773 return NO_ERROR;
4774 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004775 case 1018: { // Modify Choreographer's phase offset
4776 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004777 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004778 return NO_ERROR;
4779 }
4780 case 1019: { // Modify SurfaceFlinger's phase offset
4781 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004782 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004783 return NO_ERROR;
4784 }
Irvel468051e2016-06-13 16:44:44 -07004785 case 1020: { // Layer updates interceptor
4786 n = data.readInt32();
4787 if (n) {
4788 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004789 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004790 }
4791 else{
4792 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004793 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004794 }
4795 return NO_ERROR;
4796 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004797 case 1021: { // Disable HWC virtual displays
4798 n = data.readInt32();
4799 mUseHwcVirtualDisplays = !n;
4800 return NO_ERROR;
4801 }
Romain Guy0147a172017-06-01 13:53:56 -07004802 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004803 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004804 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004805
Chia-I Wu28f320b2018-05-03 11:02:56 -07004806 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004807 return NO_ERROR;
4808 }
Romain Guy54f154a2017-10-24 21:40:32 +01004809 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004810 int32_t colorMode;
4811
Chia-I Wu0d711262018-05-21 15:19:35 -07004812 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004813 if (data.readInt32(&colorMode) == NO_ERROR) {
4814 mForceColorMode = static_cast<ColorMode>(colorMode);
4815 }
Romain Guy54f154a2017-10-24 21:40:32 +01004816 invalidateHwcGeometry();
4817 repaintEverything();
4818 return NO_ERROR;
4819 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004820 // Deprecate, use 1030 to check whether the device is color managed.
4821 case 1024: {
4822 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004823 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004824 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004825 n = data.readInt32();
4826 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004827 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004828 Mutex::Autolock lock(mStateLock);
4829 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004830 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004831 reply->writeInt32(NO_ERROR);
4832 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004833 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004834 bool writeFile = false;
4835 {
4836 Mutex::Autolock lock(mStateLock);
4837 mTracingEnabledChanged = true;
4838 writeFile = mTracing.disable();
4839 }
4840
4841 if (writeFile) {
4842 reply->writeInt32(mTracing.writeToFile());
4843 } else {
4844 reply->writeInt32(NO_ERROR);
4845 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004846 }
4847 return NO_ERROR;
4848 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004849 case 1026: { // Get layer tracing status
4850 reply->writeBool(mTracing.isEnabled());
4851 return NO_ERROR;
4852 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004853 // Is a DisplayColorSetting supported?
4854 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004855 const auto display = getDefaultDisplayDevice();
4856 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004857 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004858 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004859
4860 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4861 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004862 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004863 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004864 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004865 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004866 reply->writeBool(true);
4867 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004868 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004869 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004870 break;
4871 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004872 reply->writeBool(
4873 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004874 break;
4875 }
4876 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004877 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004878 // Is VrFlinger active?
4879 case 1028: {
4880 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004881 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004882 return NO_ERROR;
4883 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004884 // Set buffer size for SF tracing (value in KB)
4885 case 1029: {
4886 n = data.readInt32();
4887 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4888 ALOGW("Invalid buffer size: %d KB", n);
4889 reply->writeInt32(BAD_VALUE);
4890 return BAD_VALUE;
4891 }
4892
4893 ALOGD("Updating trace buffer to %d KB", n);
4894 mTracing.setBufferSize(n * 1024);
4895 reply->writeInt32(NO_ERROR);
4896 return NO_ERROR;
4897 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004898 // Is device color managed?
4899 case 1030: {
4900 reply->writeBool(useColorManagement);
4901 return NO_ERROR;
4902 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004903 // Override default composition data space
4904 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4905 // && adb shell stop zygote && adb shell start zygote
4906 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4907 // adb shell stop zygote && adb shell start zygote
4908 case 1031: {
4909 Mutex::Autolock _l(mStateLock);
4910 n = data.readInt32();
4911 if (n) {
4912 n = data.readInt32();
4913 if (n) {
4914 Dataspace dataspace = static_cast<Dataspace>(n);
4915 if (!validateCompositionDataspace(dataspace)) {
4916 return BAD_VALUE;
4917 }
4918 mDefaultCompositionDataspace = dataspace;
4919 }
4920 n = data.readInt32();
4921 if (n) {
4922 Dataspace dataspace = static_cast<Dataspace>(n);
4923 if (!validateCompositionDataspace(dataspace)) {
4924 return BAD_VALUE;
4925 }
4926 mWideColorGamutCompositionDataspace = dataspace;
4927 }
4928 } else {
4929 // restore composition data space.
4930 mDefaultCompositionDataspace = defaultCompositionDataspace;
4931 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4932 }
4933 return NO_ERROR;
4934 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004935 // Set trace flags
4936 case 1033: {
4937 n = data.readUint32();
4938 ALOGD("Updating trace flags to 0x%x", n);
4939 mTracing.setTraceFlags(n);
4940 reply->writeInt32(NO_ERROR);
4941 return NO_ERROR;
4942 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004943 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004944 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004945 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004946 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004947 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4948 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004949 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004950 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004951 } else {
4952 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004953 }
4954 return NO_ERROR;
4955 }
Ady Abraham34392f72019-04-10 11:29:27 -07004956 case 1035: {
4957 n = data.readInt32();
4958 mDebugDisplayConfigSetByBackdoor = false;
4959 if (n >= 0) {
4960 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004961 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004962 if (result != NO_ERROR) {
4963 return result;
4964 }
4965 mDebugDisplayConfigSetByBackdoor = true;
4966 }
4967 return NO_ERROR;
4968 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004969 }
4970 }
4971 return err;
4972}
4973
Steven Thomas6d8110b2017-08-31 18:24:21 -07004974void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004975 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004976 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004977}
4978
Ana Krulec7d1d6832018-12-27 11:10:09 -08004979void SurfaceFlinger::repaintEverythingForHWC() {
4980 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004981 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004982}
4983
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004984// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4985class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004986public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004987 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4988 ~WindowDisconnector() {
4989 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004990 }
4991
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004992private:
4993 ANativeWindow* mWindow;
4994 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004995};
4996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004997status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004998 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4999 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005000 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005001 uint32_t reqWidth, uint32_t reqHeight,
5002 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005003 ISurfaceComposer::Rotation rotation,
5004 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005007 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005008
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005009 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5010
Chia-I Wu20261cb2018-08-23 12:55:44 -07005011 sp<DisplayDevice> display;
5012 {
5013 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005014
Chia-I Wu20261cb2018-08-23 12:55:44 -07005015 display = getDisplayDeviceLocked(displayToken);
5016 if (!display) return BAD_VALUE;
5017
Chia-I Wucb023152018-08-28 12:57:23 -07005018 // set the requested width/height to the logical display viewport size
5019 // by default
5020 if (reqWidth == 0 || reqHeight == 0) {
5021 reqWidth = uint32_t(display->getViewport().width());
5022 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005023 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005024 }
5025
Peiyong Lin0e003c92018-09-17 11:09:51 -07005026 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005027 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005028
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005029 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5030 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005031 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005032 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005033}
5034
chaviw93df2ea2019-04-30 16:45:12 -07005035static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5036 switch (colorMode) {
5037 case ColorMode::DISPLAY_P3:
5038 case ColorMode::BT2100_PQ:
5039 case ColorMode::BT2100_HLG:
5040 case ColorMode::DISPLAY_BT2020:
5041 return Dataspace::DISPLAY_P3;
5042 default:
5043 return Dataspace::V0_SRGB;
5044 }
5045}
5046
5047const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5048 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5049 if (displayToken) {
5050 return getDisplayDeviceLocked(displayToken);
5051 }
5052 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5053 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005054 return getDisplayByLayerStack(displayOrLayerStack);
5055}
5056
5057const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005058 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005059 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005060 return display;
5061 }
5062 }
5063 return nullptr;
5064}
5065
5066status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5067 sp<GraphicBuffer>* outBuffer) {
5068 sp<DisplayDevice> display;
5069 uint32_t width;
5070 uint32_t height;
5071 ui::Transform::orientation_flags captureOrientation;
5072 {
5073 Mutex::Autolock _l(mStateLock);
5074 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5075 if (!display) {
5076 return BAD_VALUE;
5077 }
5078
5079 width = uint32_t(display->getViewport().width());
5080 height = uint32_t(display->getViewport().height());
5081
5082 captureOrientation = fromSurfaceComposerRotation(
5083 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005084 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5085 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5086 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5087 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5088 }
chaviw93df2ea2019-04-30 16:45:12 -07005089 *outDataspace =
5090 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5091 }
5092
5093 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5094 false /* captureSecureLayers */);
5095
5096 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5097 std::placeholders::_1);
5098 bool ignored = false;
5099 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5100 false /* useIdentityTransform */,
5101 ignored /* outCapturedSecureLayers */);
5102}
5103
Robert Carr866455f2019-04-02 16:28:26 -07005104status_t SurfaceFlinger::captureLayers(
5105 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5106 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5107 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5108 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005109 ATRACE_CALL();
5110
5111 class LayerRenderArea : public RenderArea {
5112 public:
Robert Carr578038f2018-03-09 12:25:24 -08005113 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005114 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005115 bool childrenOnly, const Rect& displayViewport)
5116 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005117 mLayer(layer),
5118 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005119 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005120 mFlinger(flinger),
5121 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005122 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005123 Rect getBounds() const override {
5124 const Layer::State& layerState(mLayer->getDrawingState());
5125 return mLayer->getBufferSize(layerState);
5126 }
Marissa Wall61c58622018-07-18 10:12:20 -07005127 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005128 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005129 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005130 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005131 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005132 }
chaviwa76b2712017-09-20 12:02:26 -07005133 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005134 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005135 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005136 Rect getSourceCrop() const override {
5137 if (mCrop.isEmpty()) {
5138 return getBounds();
5139 } else {
5140 return mCrop;
5141 }
5142 }
Robert Carr578038f2018-03-09 12:25:24 -08005143 class ReparentForDrawing {
5144 public:
5145 const sp<Layer>& oldParent;
5146 const sp<Layer>& newParent;
5147
Vishnu Nair4351ad52019-02-11 14:13:02 -08005148 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5149 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005150 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005151 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005152 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5153 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005154 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005155 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005156 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005157 };
5158
5159 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005160 const Rect sourceCrop = getSourceCrop();
5161 // no need to check rotation because there is none
5162 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5163 sourceCrop.height() != getReqHeight();
5164
Robert Carr578038f2018-03-09 12:25:24 -08005165 if (!mChildrenOnly) {
5166 mTransform = mLayer->getTransform().inverse();
5167 drawLayers();
5168 } else {
5169 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005170 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5171 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005172 // In the "childrenOnly" case we reparent the children to a screenshot
5173 // layer which has no properties set and which does not draw.
5174 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005175 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5176 "Screenshot Parent"s, w, h, 0,
5177 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005178
Vishnu Nair4351ad52019-02-11 14:13:02 -08005179 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005180 drawLayers();
5181 }
5182 }
chaviwa76b2712017-09-20 12:02:26 -07005183
chaviwa76b2712017-09-20 12:02:26 -07005184 private:
chaviw7206d492017-11-10 16:16:12 -08005185 const sp<Layer> mLayer;
5186 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005187
Peiyong Linefefaac2018-08-17 12:27:51 -07005188 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005189 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005190
5191 SurfaceFlinger* mFlinger;
5192 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005193 };
5194
Robert Carrc0df3122019-04-11 13:18:21 -07005195 int reqWidth = 0;
5196 int reqHeight = 0;
5197 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005198 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005199 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005200 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005201 {
5202 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005203
Robert Carrc0df3122019-04-11 13:18:21 -07005204 parent = fromHandle(layerHandleBinder);
5205 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5206 ALOGE("captureLayers called with an invalid or removed parent");
5207 return NAME_NOT_FOUND;
5208 }
5209
5210 const int uid = IPCThreadState::self()->getCallingUid();
5211 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5212 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5213 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5214 return PERMISSION_DENIED;
5215 }
5216
Vishnu Nairefc42e22019-12-03 17:36:12 -08005217 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005218 if (sourceCrop.width() <= 0) {
5219 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005220 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005221 }
5222
5223 if (sourceCrop.height() <= 0) {
5224 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005225 crop.bottom = parentSourceBounds.getHeight();
5226 }
5227
5228 if (crop.isEmpty() || frameScale <= 0.0f) {
5229 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5230 // crop was not specified, or an invalid frame scale was provided.
5231 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005232 }
5233 reqWidth = crop.width() * frameScale;
5234 reqHeight = crop.height() * frameScale;
5235
5236 for (const auto& handle : excludeHandles) {
5237 sp<Layer> excludeLayer = fromHandle(handle);
5238 if (excludeLayer != nullptr) {
5239 excludeLayers.emplace(excludeLayer);
5240 } else {
5241 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5242 return NAME_NOT_FOUND;
5243 }
5244 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005245
5246 auto display = getDisplayByLayerStack(parent->getLayerStack());
5247 if (!display) {
5248 return BAD_VALUE;
5249 }
5250
5251 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005252 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005253
Chia-I Wu20261cb2018-08-23 12:55:44 -07005254 // really small crop or frameScale
5255 if (reqWidth <= 0) {
5256 reqWidth = 1;
5257 }
5258 if (reqHeight <= 0) {
5259 reqHeight = 1;
5260 }
5261
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005262 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5263 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005264 auto traverseLayers = [parent, childrenOnly,
5265 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005266 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5267 if (!layer->isVisible()) {
5268 return;
Robert Carr578038f2018-03-09 12:25:24 -08005269 } else if (childrenOnly && layer == parent.get()) {
5270 return;
chaviwa76b2712017-09-20 12:02:26 -07005271 }
Robert Carr866455f2019-04-02 16:28:26 -07005272
5273 sp<Layer> p = layer;
5274 while (p != nullptr) {
5275 if (excludeLayers.count(p) != 0) {
5276 return;
5277 }
5278 p = p->getParent();
5279 }
5280
chaviwa76b2712017-09-20 12:02:26 -07005281 visitor(layer);
5282 });
5283 };
Robert Carr108b2c72019-04-02 16:32:58 -07005284
5285 bool outCapturedSecureLayers = false;
5286 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5287 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005288}
5289
5290status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5291 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005292 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005293 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005294 bool useIdentityTransform,
5295 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005296 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005297
Peiyong Lin0e003c92018-09-17 11:09:51 -07005298 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005299 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5300 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005301 *outBuffer =
5302 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5303 static_cast<android_pixel_format>(reqPixelFormat), 1,
5304 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305
Robert Carr108b2c72019-04-02 16:32:58 -07005306 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5307 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005308}
5309
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005310status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5311 TraverseLayersFunction traverseLayers,
5312 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005313 bool useIdentityTransform,
5314 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005315 // This mutex protects syncFd and captureResult for communication of the return values from the
5316 // main thread back to this Binder thread
5317 std::mutex captureMutex;
5318 std::condition_variable captureCondition;
5319 std::unique_lock<std::mutex> captureLock(captureMutex);
5320 int syncFd = -1;
5321 std::optional<status_t> captureResult;
5322
Robert Carr03480e22018-01-04 16:02:06 -08005323 const int uid = IPCThreadState::self()->getCallingUid();
5324 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5325
Dominik Laskowski8c001672018-05-30 16:52:06 -07005326 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327 // If there is a refresh pending, bug out early and tell the binder thread to try again
5328 // after the refresh.
5329 if (mRefreshPending) {
5330 ATRACE_NAME("Skipping screenshot for now");
5331 std::unique_lock<std::mutex> captureLock(captureMutex);
5332 captureResult = std::make_optional<status_t>(EAGAIN);
5333 captureCondition.notify_one();
5334 return;
5335 }
5336
5337 status_t result = NO_ERROR;
5338 int fd = -1;
5339 {
5340 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005341 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005342 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005343 useIdentityTransform, forSystem, &fd,
5344 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005345 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005346 }
5347
5348 {
5349 std::unique_lock<std::mutex> captureLock(captureMutex);
5350 syncFd = fd;
5351 captureResult = std::make_optional<status_t>(result);
5352 captureCondition.notify_one();
5353 }
5354 });
5355
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005356 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005358 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359 while (*captureResult == EAGAIN) {
5360 captureResult.reset();
5361 result = postMessageAsync(message);
5362 if (result != NO_ERROR) {
5363 return result;
5364 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005365 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 }
5367 result = *captureResult;
5368 }
5369
5370 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005371 sync_wait(syncFd, -1);
5372 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005373 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005374
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005375 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005376}
5377
chaviwa76b2712017-09-20 12:02:26 -07005378void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005379 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005380 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5381 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005382 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005383
chaviwa76b2712017-09-20 12:02:26 -07005384 const auto reqWidth = renderArea.getReqWidth();
5385 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005386 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005387 const auto transform = renderArea.getTransform();
5388 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005389 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005390
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005391 renderengine::DisplaySettings clientCompositionDisplay;
5392 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005393
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005394 // assume that bounds are never offset, and that they are the same as the
5395 // buffer bounds.
5396 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005397 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005398 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005399
5400 // Now take into account the rotation flag. We append a transform that
5401 // rotates the layer stack about the origin, then translate by buffer
5402 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005403 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005404 int displacementX = 0;
5405 int displacementY = 0;
5406 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5407 switch (rotation) {
5408 case ui::Transform::ROT_90:
5409 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005410 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005411 break;
5412 case ui::Transform::ROT_180:
5413 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005414 displacementY = renderArea.getBounds().getWidth();
5415 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005416 break;
5417 case ui::Transform::ROT_270:
5418 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005419 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005420 break;
5421 default:
5422 break;
5423 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005424
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005425 // We need to transform the clipping window into the right spot.
5426 // First, rotate the clipping rectangle by the rotation hint to get the
5427 // right orientation
5428 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5429 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5430 const vec4 rotClipTL = rotMatrix * clipTL;
5431 const vec4 rotClipBR = rotMatrix * clipBR;
5432 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5433 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5434 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5435 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5436
5437 // Now reposition the clipping rectangle with the displacement vector
5438 // computed above.
5439 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005440 clientCompositionDisplay.clip =
5441 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5442 newClipRight + displacementX, newClipBottom + displacementY);
5443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005444 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005445 clientCompositionDisplay.globalTransform =
5446 clipTransform * clientCompositionDisplay.globalTransform;
5447
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005448 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5449 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005450
chaviw50da5042018-04-09 13:49:37 -07005451 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005452
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005453 renderengine::LayerSettings fillLayer;
5454 fillLayer.source.buffer.buffer = nullptr;
5455 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5456 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5457 fillLayer.alpha = half(alpha);
5458 clientCompositionLayers.push_back(fillLayer);
5459
5460 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005461 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005462 const bool supportProtectedContent = false;
5463 Region clip(renderArea.getBounds());
5464 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5465 clip,
5466 useIdentityTransform,
5467 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5468 renderArea.isSecure(),
5469 supportProtectedContent,
5470 clearRegion,
5471 };
5472 auto result = layer->prepareClientComposition(targetSettings);
5473 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005474 std::optional<renderengine::LayerSettings> shadowLayer =
5475 layer->prepareShadowClientComposition(*result, displayViewport,
5476 clientCompositionDisplay.outputDataspace);
5477 if (shadowLayer) {
5478 clientCompositionLayers.push_back(*shadowLayer);
5479 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005480 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005481 }
chaviwa76b2712017-09-20 12:02:26 -07005482 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005483
5484 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005485 // Use an empty fence for the buffer fence, since we just created the buffer so
5486 // there is no need for synchronization with the GPU.
5487 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005488 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005489 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005491 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005492
5493 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005494}
5495
chaviwa76b2712017-09-20 12:02:26 -07005496status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5497 TraverseLayersFunction traverseLayers,
5498 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005499 bool useIdentityTransform, bool forSystem,
5500 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005501 ATRACE_CALL();
5502
chaviwa76b2712017-09-20 12:02:26 -07005503 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005504 outCapturedSecureLayers =
5505 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005506 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005507
Robert Carr03480e22018-01-04 16:02:06 -08005508 // We allow the system server to take screenshots of secure layers for
5509 // use in situations like the Screen-rotation animation and place
5510 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005511 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005512 ALOGW("FB is protected: PERMISSION_DENIED");
5513 return PERMISSION_DENIED;
5514 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005515 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005516 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005517}
5518
chaviw95ef3c42019-02-14 10:55:09 -08005519void SurfaceFlinger::setInputWindowsFinished() {
5520 Mutex::Autolock _l(mStateLock);
5521
5522 mPendingSyncInputWindows = false;
5523 mTransactionCV.broadcast();
5524}
chaviw5f21a5e2019-02-14 10:00:34 -08005525
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005526// ---------------------------------------------------------------------------
5527
Dan Stoza412903f2017-04-27 13:42:17 -07005528void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5529 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005530}
5531
Dan Stoza412903f2017-04-27 13:42:17 -07005532void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5533 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005534}
5535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005536void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005537 const LayerVector::Visitor& visitor) {
5538 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005539 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005540 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005541 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005542 continue;
5543 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005544 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005545 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005546 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005547 return;
5548 }
chaviwa76b2712017-09-20 12:02:26 -07005549 if (!layer->isVisible()) {
5550 return;
5551 }
5552 visitor(layer);
5553 });
5554 }
5555}
5556
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005557status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5558 HwcConfigIndexType defaultConfig,
5559 float minRefreshRate,
5560 float maxRefreshRate) {
5561 Mutex::Autolock lock(mStateLock);
5562
Dominik Laskowski22488f62019-03-28 09:53:04 -07005563 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005564 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5565 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5566 // it should go thru setDesiredActiveConfig, similar to primary display.
5567 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5568 const auto displayId = display->getId();
5569 LOG_ALWAYS_FATAL_IF(!displayId);
5570
5571 HWC2::VsyncPeriodChangeConstraints constraints;
5572 constraints.desiredTimeNanos = systemTime();
5573 constraints.seamlessRequired = false;
5574
5575 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005576 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5577 constraints, &timeline) < 0) {
5578 return BAD_VALUE;
5579 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005580 if (timeline.refreshRequired) {
5581 repaintEverythingForHWC();
5582 }
5583
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005584 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005585 display->setActiveConfig(configId);
5586 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005587 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005588 }
5589
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005590 if (mDebugDisplayConfigSetByBackdoor) {
5591 // ignore this request as config is overridden by backdoor
5592 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005593 }
5594
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005595 bool policyChanged;
5596 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5597 &policyChanged) < 0) {
5598 return BAD_VALUE;
5599 }
5600 if (!policyChanged) {
5601 return NO_ERROR;
5602 }
5603
5604 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5605 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005606
5607 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5608 // that listeners that care about a change in allowed configs can get the notification.
5609 // Giving current ActiveConfig so that most other listeners would just drop the event
5610 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5611 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005612
Ady Abraham2139f732019-11-13 18:56:40 -08005613 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5614 auto configId = mScheduler->getPreferredConfigId();
5615 auto preferredRefreshRate = configId
5616 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5617 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5618 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5619 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5620 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5621 ALOGV("switching to Scheduler preferred config %d",
5622 preferredRefreshRate.configId.value());
5623 setDesiredActiveConfig(
5624 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5625 } else {
5626 // Set the highest allowed config
5627 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5628 Scheduler::ConfigEvent::Changed});
5629 }
5630 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005631 ALOGV("switching to config %d", defaultConfig.value());
5632 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005633 }
5634
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005635 return NO_ERROR;
5636}
5637
Ana Krulec0782b882019-10-15 17:34:54 -07005638status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005639 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005640 float maxRefreshRate) {
5641 ATRACE_CALL();
5642
5643 if (!displayToken) {
5644 return BAD_VALUE;
5645 }
5646
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005647 status_t result = NO_ERROR;
5648
Ana Krulec234bb162019-11-10 22:55:55 +01005649 postMessageSync(new LambdaMessage([&]() {
5650 const auto display = getDisplayDeviceLocked(displayToken);
5651 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005652 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005653 ALOGE("Attempt to set desired display configs for invalid display token %p",
5654 displayToken.get());
5655 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005656 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005657 ALOGW("Attempt to set desired display configs for virtual display");
5658 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005659 result =
5660 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5661 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005662 }
5663 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005664
5665 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005666}
5667
5668status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005669 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005670 float* outMinRefreshRate,
5671 float* outMaxRefreshRate) {
5672 ATRACE_CALL();
5673
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005674 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005675 return BAD_VALUE;
5676 }
5677
5678 Mutex::Autolock lock(mStateLock);
5679 const auto display = getDisplayDeviceLocked(displayToken);
5680 if (!display) {
5681 return NAME_NOT_FOUND;
5682 }
5683
5684 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005685 HwcConfigIndexType defaultConfig;
5686 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5687 *outDefaultConfig = defaultConfig.value();
5688 return NO_ERROR;
5689 } else if (display->isVirtual()) {
5690 return BAD_VALUE;
5691 } else {
5692 const auto displayId = display->getId();
5693 if (!displayId) {
5694 return BAD_VALUE;
5695 }
5696 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5697 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5698 *outMinRefreshRate = 1e9f / vsyncPeriod;
5699 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5700 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005701 }
Ana Krulec0782b882019-10-15 17:34:54 -07005702}
5703
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005704void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005705 mFlinger->setInputWindowsFinished();
5706}
5707
Robert Carrc0df3122019-04-11 13:18:21 -07005708sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005709 BBinder* b = nullptr;
5710 if (handle) {
5711 b = handle->localBinder();
5712 }
Robert Carrc0df3122019-04-11 13:18:21 -07005713 if (b == nullptr) {
5714 return nullptr;
5715 }
5716 auto it = mLayersByLocalBinderToken.find(b);
5717 if (it != mLayersByLocalBinderToken.end()) {
5718 return it->second.promote();
5719 }
5720 return nullptr;
5721}
5722
Dominik Laskowski75848362019-11-11 17:57:20 -08005723void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005724 mNumLayers++;
5725 mScheduler->registerLayer(layer);
5726}
5727
5728void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5729 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005730 removeFromOffscreenLayers(layer);
5731}
5732
5733// WARNING: ONLY CALL THIS FROM LAYER DTOR
5734// Here we add children in the current state to offscreen layers and remove the
5735// layer itself from the offscreen layer list. Since
5736// this is the dtor, it is safe to access the current state. This keeps us
5737// from dangling children layers such that they are not reachable from the
5738// Drawing state nor the offscreen layer list
5739// See b/141111965
5740void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5741 for (auto& child : layer->getCurrentChildren()) {
5742 mOffscreenLayers.emplace(child.get());
5743 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005744 mOffscreenLayers.erase(layer);
5745}
5746
Alec Mouri4545a8a2019-08-08 20:05:32 -07005747void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5748 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5749}
5750
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005751status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5752 float lightPosY, float lightPosZ,
5753 float lightRadius) {
5754 Mutex::Autolock _l(mStateLock);
5755 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5756 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5757 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5758 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5759 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5760
5761 // these values are overridden when calculating the shadow settings for a layer.
5762 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5763 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005764 return NO_ERROR;
5765}
5766
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005767} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005768
Mathias Agopian3f844832013-08-07 21:24:32 -07005769#if defined(__gl_h_)
5770#error "don't include gl/gl.h in this file"
5771#endif
5772
5773#if defined(__gl2_h_)
5774#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005775#endif