blob: ca6d941030954fcae07d1f823ee167ccf0dceb34 [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Mathias Agopianc666cae2012-07-25 18:56:13 -070040#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070041#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070071#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080073#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080075#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Jaesoo Lee43518572017-01-23 19:03:16 +0900101using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102using namespace android::hardware::configstore::V1_0;
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104// ---------------------------------------------------------------------------
105
Mathias Agopian99b49842011-06-27 16:05:52 -0700106const String16 sHardwareTest("android.permission.HARDWARE_TEST");
107const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
108const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
109const String16 sDump("android.permission.DUMP");
110
111// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800112int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
113int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Mathias Agopian99b49842011-06-27 16:05:52 -0700114
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800115SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700116 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700118 mTransactionPending(false),
119 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700120 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700121 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700122 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800123 mHwc(nullptr),
124 mRealHwc(nullptr),
125 mVrHwc(nullptr),
126 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800128 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800130 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800131 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800132 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700134 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700135 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700136 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700137 mDebugInSwapBuffers(0),
138 mLastSwapBufferTime(0),
139 mDebugInTransaction(0),
140 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700141 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700142 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800143 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000144 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700145 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700146 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800147 mHasColorMatrix(false),
148 mHasPoweredOff(false),
149 mFrameBuckets(),
150 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700151 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800152 mNumLayers(0)
153#ifdef USE_HWC2
154 ,mEnterVrMode(false)
155#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156{
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800157
158 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
159 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
160
161 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
162 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
163
Steve Blocka19954a2012-01-04 20:05:49 +0000164 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165
166 // debugging stuff...
167 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700168
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800169 // TODO (urbanus): remove once b/35319396 is fixed.
170 property_get("ro.boot.vr", value, "0");
171 mVrModeSupported = atoi(value);
172
Mathias Agopianb4b17302013-03-20 18:36:41 -0700173 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700174 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 property_get("debug.sf.showupdates", value, "0");
177 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700178
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 property_get("debug.sf.ddms", value, "0");
180 mDebugDDMS = atoi(value);
181 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700182 if (!startDdmConnection()) {
183 // start failed, and DDMS debugging not enabled
184 mDebugDDMS = 0;
185 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700187 ALOGI_IF(mDebugRegion, "showupdates enabled");
188 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700189
190 property_get("debug.sf.disable_backpressure", value, "0");
191 mPropagateBackpressure = !atoi(value);
192 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700193
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800194 property_get("debug.sf.enable_hwc_vds", value, "0");
195 mUseHwcVirtualDisplays = atoi(value);
196 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800197
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800198 property_get("ro.sf.disable_triple_buffer", value, "1");
199 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800200 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201}
202
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800203void SurfaceFlinger::onFirstRef()
204{
205 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800206}
207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208SurfaceFlinger::~SurfaceFlinger()
209{
Mathias Agopiana4912602012-07-12 14:25:33 -0700210 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
211 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
212 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800213
214 if (mVrStateCallbacks.get()) {
215 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
216 defaultServiceManager()->checkService(String16("vrmanager")));
217 if (vrManagerService.get()) {
218 vrManagerService->unregisterListener(mVrStateCallbacks);
219 }
220 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221}
222
Dan Stozac7014012014-02-14 15:03:43 -0800223void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224{
225 // the window manager died on us. prepare its eulogy.
226
Andy McFadden13a082e2012-08-24 10:16:42 -0700227 // restore initial conditions (default device unblank, etc)
228 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229
230 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700231 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800232}
233
Robert Carr1db73f62016-12-21 12:58:51 -0800234static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700235 status_t err = client->initCheck();
236 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800237 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 }
Robert Carr1db73f62016-12-21 12:58:51 -0800239 return nullptr;
240}
241
242sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
243 return initClient(new Client(this));
244}
245
246sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
247 const sp<IGraphicBufferProducer>& gbp) {
248 if (authenticateSurfaceTexture(gbp) == false) {
249 return nullptr;
250 }
251 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
252 if (layer == nullptr) {
253 return nullptr;
254 }
255
256 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257}
258
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700259sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
260 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700261{
262 class DisplayToken : public BBinder {
263 sp<SurfaceFlinger> flinger;
264 virtual ~DisplayToken() {
265 // no more references, this display must be terminated
266 Mutex::Autolock _l(flinger->mStateLock);
267 flinger->mCurrentState.displays.removeItem(this);
268 flinger->setTransactionFlags(eDisplayTransactionNeeded);
269 }
270 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700271 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700272 : flinger(flinger) {
273 }
274 };
275
276 sp<BBinder> token = new DisplayToken(this);
277
278 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700279 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700280 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700282 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700283 return token;
284}
285
Jesse Hall6c913be2013-08-08 12:15:49 -0700286void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
287 Mutex::Autolock _l(mStateLock);
288
289 ssize_t idx = mCurrentState.displays.indexOfKey(display);
290 if (idx < 0) {
291 ALOGW("destroyDisplay: invalid display token");
292 return;
293 }
294
295 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
296 if (!info.isVirtualDisplay()) {
297 ALOGE("destroyDisplay called for non-virtual display");
298 return;
299 }
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700301 mCurrentState.displays.removeItemsAt(idx);
302 setTransactionFlags(eDisplayTransactionNeeded);
303}
304
Jesse Hall692c7232012-11-08 15:41:56 -0800305void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800306 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800307 ALOGW_IF(mBuiltinDisplays[type],
308 "Overwriting display token for display type %d", type);
309 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800310 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700311 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800312 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700313 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800314}
315
Mathias Agopiane57f2922012-08-09 16:29:12 -0700316sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700317 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700318 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
319 return NULL;
320 }
Jesse Hall692c7232012-11-08 15:41:56 -0800321 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700322}
323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324void SurfaceFlinger::bootFinished()
325{
Wei Wangb254fa32017-01-31 17:43:23 -0800326 if (mStartBootAnimThread->join() != NO_ERROR) {
327 ALOGE("Join StartBootAnimThread failed!");
328 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 const nsecs_t now = systemTime();
330 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000331 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700332 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700333
334 // wait patiently for the window manager death
335 const String16 name("window");
336 sp<IBinder> window(defaultServiceManager()->getService(name));
337 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700338 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700339 }
340
341 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700342 // formerly we would just kill the process, but we now ask it to exit so it
343 // can choose where to stop the animation.
344 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700345
346 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
347 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
348 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800349
350 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
351 defaultServiceManager()->checkService(String16("vrmanager")));
352 if (vrManagerService.get()) {
353 mVrStateCallbacks = new VrStateCallbacks(*this);
354 vrManagerService->registerListener(mVrStateCallbacks);
355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356}
357
Mathias Agopian3f844832013-08-07 21:24:32 -0700358void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700359 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700360 RenderEngine& engine;
361 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700362 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700363 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
364 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700365 }
366 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700367 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700368 return true;
369 }
370 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700371 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700372}
373
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374class DispSyncSource : public VSyncSource, private DispSync::Callback {
375public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700376 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000377 const char* name) :
378 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700379 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700380 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000381 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
382 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700383 mDispSync(dispSync),
384 mCallbackMutex(),
385 mCallback(),
386 mVsyncMutex(),
387 mPhaseOffset(phaseOffset),
388 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700389
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700390 virtual ~DispSyncSource() {}
391
392 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700393 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396 static_cast<DispSync::Callback*>(this));
397 if (err != NO_ERROR) {
398 ALOGE("error registering vsync callback: %s (%d)",
399 strerror(-err), err);
400 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700401 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700402 } else {
403 status_t err = mDispSync->removeEventListener(
404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error unregistering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700409 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700411 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 }
413
414 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 mCallback = callback;
417 }
418
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 virtual void setPhaseOffset(nsecs_t phaseOffset) {
420 Mutex::Autolock lock(mVsyncMutex);
421
422 // Normalize phaseOffset to [0, period)
423 auto period = mDispSync->getPeriod();
424 phaseOffset %= period;
425 if (phaseOffset < 0) {
426 // If we're here, then phaseOffset is in (-period, 0). After this
427 // operation, it will be in (0, period)
428 phaseOffset += period;
429 }
430 mPhaseOffset = phaseOffset;
431
432 // If we're not enabled, we don't need to mess with the listeners
433 if (!mEnabled) {
434 return;
435 }
436
437 // Remove the listener with the old offset
438 status_t err = mDispSync->removeEventListener(
439 static_cast<DispSync::Callback*>(this));
440 if (err != NO_ERROR) {
441 ALOGE("error unregistering vsync callback: %s (%d)",
442 strerror(-err), err);
443 }
444
445 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000446 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700447 static_cast<DispSync::Callback*>(this));
448 if (err != NO_ERROR) {
449 ALOGE("error registering vsync callback: %s (%d)",
450 strerror(-err), err);
451 }
452 }
453
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454private:
455 virtual void onDispSyncEvent(nsecs_t when) {
456 sp<VSyncSource::Callback> callback;
457 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700458 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459 callback = mCallback;
460
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700461 if (mTraceVsync) {
462 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700463 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700464 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 }
466
467 if (callback != NULL) {
468 callback->onVSyncEvent(when);
469 }
470 }
471
Tim Murray4a4e4a22016-04-19 16:29:23 +0000472 const char* const mName;
473
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 int mValue;
475
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700476 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 const String8 mVsyncOnLabel;
478 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700479
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700481
482 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700484
485 Mutex mVsyncMutex; // Protects the following
486 nsecs_t mPhaseOffset;
487 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488};
489
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700490class InjectVSyncSource : public VSyncSource {
491public:
492 InjectVSyncSource() {}
493
494 virtual ~InjectVSyncSource() {}
495
496 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
497 std::lock_guard<std::mutex> lock(mCallbackMutex);
498 mCallback = callback;
499 }
500
501 virtual void onInjectSyncEvent(nsecs_t when) {
502 std::lock_guard<std::mutex> lock(mCallbackMutex);
503 mCallback->onVSyncEvent(when);
504 }
505
506 virtual void setVSyncEnabled(bool) {}
507 virtual void setPhaseOffset(nsecs_t) {}
508
509private:
510 std::mutex mCallbackMutex; // Protects the following
511 sp<VSyncSource::Callback> mCallback;
512};
513
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700515 ALOGI( "SurfaceFlinger's main thread ready to run. "
516 "Initializing graphics H/W...");
517
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900518 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
519
Dan Stoza9e56aa02015-11-02 13:00:03 -0800520 { // Autolock scope
521 Mutex::Autolock _l(mStateLock);
522
523 // initialize EGL for the default display
524 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
525 eglInitialize(mEGLDisplay, NULL, NULL);
526
527 // start the EventThread
528 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
529 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700530 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800531 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
532 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700533 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800534 mEventQueue.setEventThread(mSFEventThread);
535
Tim Murrayacff43d2016-07-29 13:57:24 -0700536 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700537 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700538 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700539 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
540 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
541 }
542
Dan Stoza9e56aa02015-11-02 13:00:03 -0800543 // Get a RenderEngine for the given display / config (can't fail)
544 mRenderEngine = RenderEngine::create(mEGLDisplay,
545 HAL_PIXEL_FORMAT_RGBA_8888);
546 }
547
548 // Drop the state lock while we initialize the hardware composer. We drop
549 // the lock because on creation, it will call back into SurfaceFlinger to
550 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800551 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800552 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800553 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800554 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
555
Jesse Hall692c7232012-11-08 15:41:56 -0800556 Mutex::Autolock _l(mStateLock);
557
Mathias Agopian875d8e12013-06-07 15:35:48 -0700558 // retrieve the EGL context that was selected/created
559 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700560
Mathias Agopianda27af92012-09-13 18:17:13 -0700561 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
562 "couldn't create EGLContext");
563
Dan Stoza9e56aa02015-11-02 13:00:03 -0800564 // make the GLContext current so that we can create textures when creating
565 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700566 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
567
Jamie Gennisd1700752013-10-14 12:22:52 -0700568 mEventControlThread = new EventControlThread(this);
569 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
570
Mathias Agopian92a979a2012-08-02 18:32:23 -0700571 // initialize our drawing state
572 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700573
Andy McFadden13a082e2012-08-24 10:16:42 -0700574 // set initial conditions (e.g. unblank default device)
575 initializeDisplays();
576
Dan Stoza4e637772016-07-28 13:31:51 -0700577 mRenderEngine->primeCache();
578
Wei Wangb254fa32017-01-31 17:43:23 -0800579 mStartBootAnimThread = new StartBootAnimThread();
580 if (mStartBootAnimThread->Start() != NO_ERROR) {
581 ALOGE("Run StartBootAnimThread failed!");
582 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700585}
586
Mathias Agopiana67e4182012-06-19 17:26:12 -0700587void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800588 // Start boot animation service by setting a property mailbox
589 // if property setting thread is already running, Start() will be just a NOP
590 mStartBootAnimThread->Start();
591 // Wait until property was set
592 if (mStartBootAnimThread->join() != NO_ERROR) {
593 ALOGE("Join StartBootAnimThread failed!");
594 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700595}
596
Mathias Agopian875d8e12013-06-07 15:35:48 -0700597size_t SurfaceFlinger::getMaxTextureSize() const {
598 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700599}
600
Mathias Agopian875d8e12013-06-07 15:35:48 -0700601size_t SurfaceFlinger::getMaxViewportDims() const {
602 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700603}
604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800605// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800606
Jamie Gennis582270d2011-08-17 18:19:00 -0700607bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800608 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800609 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800610 return authenticateSurfaceTextureLocked(bufferProducer);
611}
612
613bool SurfaceFlinger::authenticateSurfaceTextureLocked(
614 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800615 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700616 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800617}
618
Brian Anderson069b3652016-07-22 10:32:47 -0700619status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700620 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700621 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700622 FrameEvent::REQUESTED_PRESENT,
623 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700624 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700625 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700626 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700627 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700628 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700629 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700630 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700631 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700632 };
633 return NO_ERROR;
634}
635
Dan Stoza7f7da322014-05-02 15:26:25 -0700636status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
637 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700638 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700639 return BAD_VALUE;
640 }
641
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500642 if (!display.get())
643 return NAME_NOT_FOUND;
644
Jesse Hall692c7232012-11-08 15:41:56 -0800645 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700646 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800647 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700648 type = i;
649 break;
650 }
651 }
652
653 if (type < 0) {
654 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700655 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700656
Mathias Agopian8b736f12012-08-13 17:54:26 -0700657 // TODO: Not sure if display density should handled by SF any longer
658 class Density {
659 static int getDensityFromProperty(char const* propName) {
660 char property[PROPERTY_VALUE_MAX];
661 int density = 0;
662 if (property_get(propName, property, NULL) > 0) {
663 density = atoi(property);
664 }
665 return density;
666 }
667 public:
668 static int getEmuDensity() {
669 return getDensityFromProperty("qemu.sf.lcd_density"); }
670 static int getBuildDensity() {
671 return getDensityFromProperty("ro.sf.lcd_density"); }
672 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700673
Dan Stoza7f7da322014-05-02 15:26:25 -0700674 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700677 DisplayInfo info = DisplayInfo();
678
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679 float xdpi = hwConfig->getDpiX();
680 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700681
682 if (type == DisplayDevice::DISPLAY_PRIMARY) {
683 // The density of the device is provided by a build property
684 float density = Density::getBuildDensity() / 160.0f;
685 if (density == 0) {
686 // the build doesn't provide a density -- this is wrong!
687 // use xdpi instead
688 ALOGE("ro.sf.lcd_density must be defined as a build property");
689 density = xdpi / 160.0f;
690 }
691 if (Density::getEmuDensity()) {
692 // if "qemu.sf.lcd_density" is specified, it overrides everything
693 xdpi = ydpi = density = Density::getEmuDensity();
694 density /= 160.0f;
695 }
696 info.density = density;
697
698 // TODO: this needs to go away (currently needed only by webkit)
699 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
700 info.orientation = hw->getOrientation();
701 } else {
702 // TODO: where should this value come from?
703 static const int TV_DENSITY = 213;
704 info.density = TV_DENSITY / 160.0f;
705 info.orientation = 0;
706 }
707
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 info.w = hwConfig->getWidth();
709 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700710 info.xdpi = xdpi;
711 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800712 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900713 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714
Andy McFadden91b2ca82014-06-13 14:04:23 -0700715 // This is how far in advance a buffer must be queued for
716 // presentation at a given time. If you want a buffer to appear
717 // on the screen at time N, you must submit the buffer before
718 // (N - presentationDeadline).
719 //
720 // Normally it's one full refresh period (to give SF a chance to
721 // latch the buffer), but this can be reduced by configuring a
722 // DispSync offset. Any additional delays introduced by the hardware
723 // composer or panel must be accounted for here.
724 //
725 // We add an additional 1ms to allow for processing time and
726 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800728 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700729
730 // All non-virtual displays are currently considered secure.
731 info.secure = true;
732
Michael Wright28f24d02016-07-12 13:30:53 -0700733 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700734 }
735
Dan Stoza7f7da322014-05-02 15:26:25 -0700736 return NO_ERROR;
737}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700738
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800739status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700740 DisplayStatInfo* stats) {
741 if (stats == NULL) {
742 return BAD_VALUE;
743 }
744
745 // FIXME for now we always return stats for the primary display
746 memset(stats, 0, sizeof(*stats));
747 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
748 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
749 return NO_ERROR;
750}
751
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700752int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800753 if (display == NULL) {
754 ALOGE("%s : display is NULL", __func__);
755 return BAD_VALUE;
756 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700757 sp<DisplayDevice> device(getDisplayDevice(display));
758 if (device != NULL) {
759 return device->getActiveConfig();
760 }
761 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700762}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700763
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700764void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
765 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
766 this);
767 int32_t type = hw->getDisplayType();
768 int currentMode = hw->getActiveConfig();
769
770 if (mode == currentMode) {
771 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
772 return;
773 }
774
775 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
776 ALOGW("Trying to set config for virtual display");
777 return;
778 }
779
780 hw->setActiveConfig(mode);
781 getHwComposer().setActiveConfig(type, mode);
782}
783
784status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
785 class MessageSetActiveConfig: public MessageBase {
786 SurfaceFlinger& mFlinger;
787 sp<IBinder> mDisplay;
788 int mMode;
789 public:
790 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
791 int mode) :
792 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
793 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700794 Vector<DisplayInfo> configs;
795 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700796 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700797 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700798 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700799 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700800 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700801 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
802 if (hw == NULL) {
803 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700804 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700805 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
806 ALOGW("Attempt to set active config = %d for virtual display",
807 mMode);
808 } else {
809 mFlinger.setActiveConfigInternal(hw, mMode);
810 }
811 return true;
812 }
813 };
814 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
815 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700816 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817}
Michael Wright28f24d02016-07-12 13:30:53 -0700818status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
819 Vector<android_color_mode_t>* outColorModes) {
820 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
821 return BAD_VALUE;
822 }
823
824 if (!display.get()) {
825 return NAME_NOT_FOUND;
826 }
827
828 int32_t type = NAME_NOT_FOUND;
829 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
830 if (display == mBuiltinDisplays[i]) {
831 type = i;
832 break;
833 }
834 }
835
836 if (type < 0) {
837 return type;
838 }
839
840 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
841 outColorModes->clear();
842 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
843
844 return NO_ERROR;
845}
846
847android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
848 sp<DisplayDevice> device(getDisplayDevice(display));
849 if (device != nullptr) {
850 return device->getActiveColorMode();
851 }
852 return static_cast<android_color_mode_t>(BAD_VALUE);
853}
854
855void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
856 android_color_mode_t mode) {
857 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
858 this);
859 int32_t type = hw->getDisplayType();
860 android_color_mode_t currentMode = hw->getActiveColorMode();
861
862 if (mode == currentMode) {
863 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
864 return;
865 }
866
867 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
868 ALOGW("Trying to set config for virtual display");
869 return;
870 }
871
872 hw->setActiveColorMode(mode);
873 getHwComposer().setActiveColorMode(type, mode);
874}
875
876
877status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
878 android_color_mode_t colorMode) {
879 class MessageSetActiveColorMode: public MessageBase {
880 SurfaceFlinger& mFlinger;
881 sp<IBinder> mDisplay;
882 android_color_mode_t mMode;
883 public:
884 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
885 android_color_mode_t mode) :
886 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
887 virtual bool handler() {
888 Vector<android_color_mode_t> modes;
889 mFlinger.getDisplayColorModes(mDisplay, &modes);
890 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
891 if (mMode < 0 || !exists) {
892 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
893 mDisplay.get());
894 return true;
895 }
896 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
897 if (hw == nullptr) {
898 ALOGE("Attempt to set active color mode = %d for null display %p",
899 mMode, mDisplay.get());
900 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
901 ALOGW("Attempt to set active color mode= %d for virtual display",
902 mMode);
903 } else {
904 mFlinger.setActiveColorModeInternal(hw, mMode);
905 }
906 return true;
907 }
908 };
909 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
910 postMessageSync(msg);
911 return NO_ERROR;
912}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700913
Svetoslavd85084b2014-03-20 10:28:31 -0700914status_t SurfaceFlinger::clearAnimationFrameStats() {
915 Mutex::Autolock _l(mStateLock);
916 mAnimFrameTracker.clearStats();
917 return NO_ERROR;
918}
919
920status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
921 Mutex::Autolock _l(mStateLock);
922 mAnimFrameTracker.getStats(outStats);
923 return NO_ERROR;
924}
925
Dan Stozac4f471e2016-03-24 09:31:08 -0700926status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
927 HdrCapabilities* outCapabilities) const {
928 Mutex::Autolock _l(mStateLock);
929
930 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
931 if (displayDevice == nullptr) {
932 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
933 return BAD_VALUE;
934 }
935
936 std::unique_ptr<HdrCapabilities> capabilities =
937 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
938 if (capabilities) {
939 std::swap(*outCapabilities, *capabilities);
940 } else {
941 return BAD_VALUE;
942 }
943
944 return NO_ERROR;
945}
946
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700947status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
948 if (enable == mInjectVSyncs) {
949 return NO_ERROR;
950 }
951
952 if (enable) {
953 mInjectVSyncs = enable;
954 ALOGV("VSync Injections enabled");
955 if (mVSyncInjector.get() == nullptr) {
956 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700957 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700958 }
959 mEventQueue.setEventThread(mInjectorEventThread);
960 } else {
961 mInjectVSyncs = enable;
962 ALOGV("VSync Injections disabled");
963 mEventQueue.setEventThread(mSFEventThread);
964 mVSyncInjector.clear();
965 }
966 return NO_ERROR;
967}
968
969status_t SurfaceFlinger::injectVSync(nsecs_t when) {
970 if (!mInjectVSyncs) {
971 ALOGE("VSync Injections not enabled");
972 return BAD_VALUE;
973 }
974 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
975 ALOGV("Injecting VSync inside SurfaceFlinger");
976 mVSyncInjector->onInjectSyncEvent(when);
977 }
978 return NO_ERROR;
979}
980
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800981// ----------------------------------------------------------------------------
982
983sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800984 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700985}
986
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800987// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800988
989void SurfaceFlinger::waitForEvent() {
990 mEventQueue.waitMessage();
991}
992
993void SurfaceFlinger::signalTransaction() {
994 mEventQueue.invalidate();
995}
996
997void SurfaceFlinger::signalLayerUpdate() {
998 mEventQueue.invalidate();
999}
1000
1001void SurfaceFlinger::signalRefresh() {
1002 mEventQueue.refresh();
1003}
1004
1005status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001006 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001007 return mEventQueue.postMessage(msg, reltime);
1008}
1009
1010status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001011 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001012 status_t res = mEventQueue.postMessage(msg, reltime);
1013 if (res == NO_ERROR) {
1014 msg->wait();
1015 }
1016 return res;
1017}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001018
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001019void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001020 do {
1021 waitForEvent();
1022 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001023}
1024
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001025void SurfaceFlinger::enableHardwareVsync() {
1026 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001027 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001028 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001029 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1030 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001031 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001032 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001033}
1034
Jesse Hall948fe0c2013-10-14 12:56:09 -07001035void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001036 Mutex::Autolock _l(mHWVsyncLock);
1037
Jesse Hall948fe0c2013-10-14 12:56:09 -07001038 if (makeAvailable) {
1039 mHWVsyncAvailable = true;
1040 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001041 // Hardware vsync is not currently available, so abort the resync
1042 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001043 return;
1044 }
1045
Dan Stoza9e56aa02015-11-02 13:00:03 -08001046 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1047 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001048
1049 mPrimaryDispSync.reset();
1050 mPrimaryDispSync.setPeriod(period);
1051
1052 if (!mPrimaryHWVsyncEnabled) {
1053 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001054 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1055 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001056 mPrimaryHWVsyncEnabled = true;
1057 }
1058}
1059
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061 Mutex::Autolock _l(mHWVsyncLock);
1062 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001063 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1064 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 mPrimaryDispSync.endResync();
1066 mPrimaryHWVsyncEnabled = false;
1067 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001068 if (makeUnavailable) {
1069 mHWVsyncAvailable = false;
1070 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071}
1072
Tim Murray4a4e4a22016-04-19 16:29:23 +00001073void SurfaceFlinger::resyncWithRateLimit() {
1074 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1075 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001076 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001077 }
1078}
1079
Steven Thomas3cfac282017-02-06 12:29:30 -08001080void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1081 nsecs_t timestamp) {
1082 Mutex::Autolock lock(mStateLock);
1083 // Ignore any vsyncs from the non-active hardware composer.
1084 if (composer != mHwc) {
1085 return;
1086 }
1087
Jamie Gennisd1700752013-10-14 12:22:52 -07001088 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089
Jamie Gennisd1700752013-10-14 12:22:52 -07001090 { // Scope for the lock
1091 Mutex::Autolock _l(mHWVsyncLock);
1092 if (type == 0 && mPrimaryHWVsyncEnabled) {
1093 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001094 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001095 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001096
1097 if (needsHwVsync) {
1098 enableHardwareVsync();
1099 } else {
1100 disableHardwareVsync(false);
1101 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001102}
1103
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001104void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1105 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1106 *compositorTiming = mCompositorTiming;
1107}
1108
Dan Stoza9e56aa02015-11-02 13:00:03 -08001109void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1110 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1111 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1112 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001113
Dan Stoza9e56aa02015-11-02 13:00:03 -08001114 // All non-virtual displays are currently considered secure.
1115 bool isSecure = true;
1116
1117 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001118
1119 // When we're using the vr composer, the assumption is that we've
1120 // already created the IBinder object for the primary display.
1121 if (!mHwc->isUsingVrComposer()) {
1122 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1123 }
1124
Dan Stoza9e56aa02015-11-02 13:00:03 -08001125 wp<IBinder> token = mBuiltinDisplays[type];
1126
1127 sp<IGraphicBufferProducer> producer;
1128 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001129 BufferQueue::createBufferQueue(&producer, &consumer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001130
1131 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1132 DisplayDevice::DISPLAY_PRIMARY, consumer);
1133 sp<DisplayDevice> hw = new DisplayDevice(this,
1134 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1135 producer, mRenderEngine->getEGLConfig());
1136 mDisplays.add(token, hw);
1137 } else {
1138 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001139 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001140 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001142 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001143 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1144 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001145 }
1146 setTransactionFlags(eDisplayTransactionNeeded);
1147
Andy McFadden9e9689c2012-10-10 18:17:51 -07001148 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001149 }
Mathias Agopian86303202012-07-24 22:46:10 -07001150}
1151
Steven Thomas3cfac282017-02-06 12:29:30 -08001152void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1153 Mutex::Autolock lock(mStateLock);
1154 if (composer == mHwc) {
1155 repaintEverything();
1156 } else {
1157 // This isn't from our current hardware composer. If it's a callback
1158 // from the real composer, forward the refresh request to vr
1159 // flinger. Otherwise ignore it.
1160 if (!composer->isUsingVrComposer()) {
1161 mVrFlinger->OnHardwareComposerRefresh();
1162 }
1163 }
1164}
1165
Dan Stoza9e56aa02015-11-02 13:00:03 -08001166void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001168 getHwComposer().setVsyncEnabled(disp,
1169 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001170}
1171
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001172void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1173 for (size_t i = 0; i < layers.size(); ++i) {
1174 layers[i]->clearHwcLayers();
1175 }
1176}
1177
1178void SurfaceFlinger::resetHwc() {
1179 disableHardwareVsync(true);
1180 clearHwcLayers(mDrawingState.layersSortedByZ);
1181 clearHwcLayers(mCurrentState.layersSortedByZ);
1182 // Clear the drawing state so that the logic inside of
1183 // handleTransactionLocked will fire. It will determine the delta between
1184 // mCurrentState and mDrawingState and re-apply all changes when we make the
1185 // transition.
1186 mDrawingState.displays.clear();
1187 mDisplays.clear();
1188}
1189
1190void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001191 bool enteringVrMode = mEnterVrMode;
1192 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1193 return;
1194 }
1195 if (enteringVrMode && !mVrHwc) {
1196 // Construct new HWComposer without holding any locks.
1197 mVrHwc = new HWComposer(true);
1198 ALOGV("Vr HWC created");
1199 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001200 {
1201 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001202
1203 if (enteringVrMode) {
1204 // Start vrflinger thread, if it hasn't been started already.
1205 if (!mVrFlinger) {
1206 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1207 int err = mVrFlinger->Run(mHwc->getComposer());
1208 if (err != NO_ERROR) {
1209 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1210 mVrFlinger.reset();
1211 mEnterVrMode = false;
1212 return;
1213 }
1214 }
1215
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001216 resetHwc();
1217
1218 mHwc = mVrHwc;
1219 mVrFlinger->EnterVrMode();
1220 } else {
1221 mVrFlinger->ExitVrMode();
1222
1223 resetHwc();
1224
1225 mHwc = mRealHwc;
1226 enableHardwareVsync();
1227 }
1228
1229 mVisibleRegionsDirty = true;
1230 invalidateHwcGeometry();
1231 android_atomic_or(1, &mRepaintEverything);
1232 setTransactionFlags(eDisplayTransactionNeeded);
1233 }
1234 if (mVrHwc) {
1235 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1236 }
1237}
1238
Mathias Agopian4fec8732012-06-29 14:12:52 -07001239void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001240 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001241 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001242 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001243 // TODO(eieio): Tied to a conditional until SELinux issues
1244 // are resolved.
1245 if (mVrModeSupported) {
1246 updateVrMode();
1247 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001248
Dan Stoza50182882016-07-08 12:02:20 -07001249 bool frameMissed = !mHadClientComposition &&
1250 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001251 (mPreviousPresentFence->getSignalTime() ==
1252 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001253 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001254 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001255 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001256 signalLayerUpdate();
1257 break;
1258 }
1259
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 bool refreshNeeded = handleMessageTransaction();
1261 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001262 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001263 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001264 // Signal a refresh if a transaction modified the window state,
1265 // a new buffer was latched, or if HWC has requested a full
1266 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001267 signalRefresh();
1268 }
1269 break;
1270 }
1271 case MessageQueue::REFRESH: {
1272 handleMessageRefresh();
1273 break;
1274 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001275 }
1276}
1277
Dan Stoza6b9454d2014-11-07 16:00:59 -08001278bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001279 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001280 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001281 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001283 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001284 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001285}
1286
Dan Stoza6b9454d2014-11-07 16:00:59 -08001287bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001288 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001290}
1291
1292void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001293 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001294
Pablo Ceballos40845df2016-01-25 17:41:15 -08001295 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001296
Brian Andersond6927fb2016-07-23 23:37:30 -07001297 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001298 rebuildLayerStacks();
1299 setUpHWComposer();
1300 doDebugFlashRegions();
1301 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001302 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001303
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001304 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001305
1306 mHadClientComposition = false;
1307 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1308 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1309 mHadClientComposition = mHadClientComposition ||
1310 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1311 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001312
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001314}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001315
Mathias Agopiancd60f992012-08-16 16:28:27 -07001316void SurfaceFlinger::doDebugFlashRegions()
1317{
1318 // is debugging enabled
1319 if (CC_LIKELY(!mDebugRegion))
1320 return;
1321
1322 const bool repaintEverything = mRepaintEverything;
1323 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1324 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001325 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001326 // transform the dirty region into this screen's coordinate space
1327 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1328 if (!dirtyRegion.isEmpty()) {
1329 // redraw the whole screen
1330 doComposeSurfaces(hw, Region(hw->bounds()));
1331
1332 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001334 RenderEngine& engine(getRenderEngine());
1335 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1336
Mathias Agopianda27af92012-09-13 18:17:13 -07001337 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338 }
1339 }
1340 }
1341
1342 postFramebuffer();
1343
1344 if (mDebugRegion > 1) {
1345 usleep(mDebugRegion * 1000);
1346 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001347
Dan Stoza9e56aa02015-11-02 13:00:03 -08001348 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001349 auto& displayDevice = mDisplays[displayId];
1350 if (!displayDevice->isDisplayOn()) {
1351 continue;
1352 }
1353
1354 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1356 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001357 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001358}
1359
Brian Andersond6927fb2016-07-23 23:37:30 -07001360void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001361{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001362 ATRACE_CALL();
1363 ALOGV("preComposition");
1364
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001366 mDrawingState.traverseInZOrder([&](Layer* layer) {
1367 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001368 needExtraInvalidate = true;
1369 }
Robert Carr2047fae2016-11-28 14:09:09 -08001370 });
1371
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 if (needExtraInvalidate) {
1373 signalLayerUpdate();
1374 }
1375}
1376
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001377void SurfaceFlinger::updateCompositorTiming(
1378 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1379 std::shared_ptr<FenceTime>& presentFenceTime) {
1380 // Update queue of past composite+present times and determine the
1381 // most recently known composite to present latency.
1382 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1383 nsecs_t compositeToPresentLatency = -1;
1384 while (!mCompositePresentTimes.empty()) {
1385 CompositePresentTime& cpt = mCompositePresentTimes.front();
1386 // Cached values should have been updated before calling this method,
1387 // which helps avoid duplicate syscalls.
1388 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1389 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1390 break;
1391 }
1392 compositeToPresentLatency = displayTime - cpt.composite;
1393 mCompositePresentTimes.pop();
1394 }
1395
1396 // Don't let mCompositePresentTimes grow unbounded, just in case.
1397 while (mCompositePresentTimes.size() > 16) {
1398 mCompositePresentTimes.pop();
1399 }
1400
1401 // Integer division and modulo round toward 0 not -inf, so we need to
1402 // treat negative and positive offsets differently.
1403 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1404 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1405 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1406
1407 // Snap the latency to a value that removes scheduling jitter from the
1408 // composition and present times, which often have >1ms of jitter.
1409 // Reducing jitter is important if an app attempts to extrapolate
1410 // something (such as user input) to an accurate diasplay time.
1411 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1412 // with (presentLatency % interval).
1413 nsecs_t snappedCompositeToPresentLatency = -1;
1414 if (compositeToPresentLatency >= 0) {
1415 nsecs_t bias = vsyncInterval / 2;
1416 int64_t extraVsyncs =
1417 (compositeToPresentLatency - idealLatency + bias) /
1418 vsyncInterval;
1419 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1420 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1421 }
1422
1423 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1424 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1425 mCompositorTiming.interval = vsyncInterval;
1426 if (snappedCompositeToPresentLatency >= 0) {
1427 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1428 }
1429}
1430
1431void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001432{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 ATRACE_CALL();
1434 ALOGV("postComposition");
1435
Brian Anderson3546a3f2016-07-14 11:51:14 -07001436 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001437 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001438 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001439 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001440 }
1441
Brian Andersond6927fb2016-07-23 23:37:30 -07001442 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001443
1444 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1445 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1446 glCompositionDoneFenceTime =
1447 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1448 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1449 } else {
1450 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1451 }
1452 mGlCompositionDoneTimeline.updateSignalTimes();
1453
1454 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1455 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1456 mDisplayTimeline.push(displayFenceTime);
1457 mDisplayTimeline.updateSignalTimes();
1458
1459 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1460 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1461 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1462 presentFenceTime = &displayFenceTime;
1463 } else {
1464 retireFenceTime = &displayFenceTime;
1465 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001466
1467 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1468 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1469
1470 // We use the refreshStartTime which might be sampled a little later than
1471 // when we started doing work for this frame, but that should be okay
1472 // since updateCompositorTiming has snapping logic.
1473 updateCompositorTiming(
1474 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1475
Robert Carr2047fae2016-11-28 14:09:09 -08001476 mDrawingState.traverseInZOrder([&](Layer* layer) {
1477 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001479 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001480 recordBufferingStats(layer->getName().string(),
1481 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001482 }
Robert Carr2047fae2016-11-28 14:09:09 -08001483 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001484
Brian Anderson3d4039d2016-09-23 16:31:30 -07001485 if (displayFence->isValid()) {
1486 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001487 enableHardwareVsync();
1488 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001489 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001490 }
1491 }
1492
Andy McFadden5167ec62014-05-22 13:08:43 -07001493 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001494 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001495 enableHardwareVsync();
1496 }
1497 }
1498
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001499 if (mAnimCompositionPending) {
1500 mAnimCompositionPending = false;
1501
Brian Anderson3d4039d2016-09-23 16:31:30 -07001502 if (displayFenceTime->isValid()) {
1503 mAnimFrameTracker.setActualPresentFence(
1504 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001505 } else {
1506 // The HWC doesn't support present fences, so use the refresh
1507 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001508 nsecs_t presentTime =
1509 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001510 mAnimFrameTracker.setActualPresentTime(presentTime);
1511 }
1512 mAnimFrameTracker.advanceFrame();
1513 }
Dan Stozab90cf072015-03-05 11:05:59 -08001514
1515 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1516 return;
1517 }
1518
1519 nsecs_t currentTime = systemTime();
1520 if (mHasPoweredOff) {
1521 mHasPoweredOff = false;
1522 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001523 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001525 if (numPeriods < NUM_BUCKETS - 1) {
1526 mFrameBuckets[numPeriods] += elapsedTime;
1527 } else {
1528 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1529 }
1530 mTotalTime += elapsedTime;
1531 }
1532 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533}
1534
1535void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 ATRACE_CALL();
1537 ALOGV("rebuildLayerStacks");
1538
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001540 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1541 ATRACE_CALL();
1542 mVisibleRegionsDirty = false;
1543 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001544
Jeff Sharkey76488112017-02-27 14:15:18 -07001545 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1546 Region opaqueRegion;
1547 Region dirtyRegion;
1548 Vector<sp<Layer>> layersSortedByZ;
1549 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1550 const Transform& tr(displayDevice->getTransform());
1551 const Rect bounds(displayDevice->getBounds());
1552 if (displayDevice->isDisplayOn()) {
1553 computeVisibleRegions(
1554 displayDevice->getLayerStack(), dirtyRegion,
1555 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001556
Jeff Sharkey76488112017-02-27 14:15:18 -07001557 mDrawingState.traverseInZOrder([&](Layer* layer) {
1558 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1559 Region drawRegion(tr.transform(
1560 layer->visibleNonTransparentRegion));
1561 drawRegion.andSelf(bounds);
1562 if (!drawRegion.isEmpty()) {
1563 layersSortedByZ.add(layer);
1564 } else {
1565 // Clear out the HWC layer if this layer was
1566 // previously visible, but no longer is
1567 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1568 nullptr);
1569 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001570 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001571 // WM changes displayDevice->layerStack upon sleep/awake.
1572 // Here we make sure we delete the HWC layers even if
1573 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001574 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1575 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001576 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001577 });
1578 }
1579 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1580 displayDevice->undefinedRegion.set(bounds);
1581 displayDevice->undefinedRegion.subtractSelf(
1582 tr.transform(opaqueRegion));
1583 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001584 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001585 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001589 ATRACE_CALL();
1590 ALOGV("setUpHWComposer");
1591
Jesse Hall028dc8f2013-08-20 16:35:32 -07001592 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001593 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1594 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1595 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1596
1597 // If nothing has changed (!dirty), don't recompose.
1598 // If something changed, but we don't currently have any visible layers,
1599 // and didn't when we last did a composition, then skip it this time.
1600 // The second rule does two things:
1601 // - When all layers are removed from a display, we'll emit one black
1602 // frame, then nothing more until we get new layers.
1603 // - When a display is created with a private layer stack, we won't
1604 // emit any black frames until a layer is added to the layer stack.
1605 bool mustRecompose = dirty && !(empty && wasEmpty);
1606
1607 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1608 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1609 mustRecompose ? "doing" : "skipping",
1610 dirty ? "+" : "-",
1611 empty ? "+" : "-",
1612 wasEmpty ? "+" : "-");
1613
Dan Stoza71433162014-02-04 16:22:36 -08001614 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001615
1616 if (mustRecompose) {
1617 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1618 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001619 }
1620
Dan Stoza9e56aa02015-11-02 13:00:03 -08001621 // build the h/w work list
1622 if (CC_UNLIKELY(mGeometryInvalid)) {
1623 mGeometryInvalid = false;
1624 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1625 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1626 const auto hwcId = displayDevice->getHwcDisplayId();
1627 if (hwcId >= 0) {
1628 const Vector<sp<Layer>>& currentLayers(
1629 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001630 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001631 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001632 if (!layer->hasHwcLayer(hwcId)) {
1633 auto hwcLayer = mHwc->createLayer(hwcId);
1634 if (hwcLayer) {
1635 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1636 } else {
1637 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001638 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001639 }
1640 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001641
Robert Carrae060832016-11-28 10:51:00 -08001642 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001643 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001645 }
1646 }
1647 }
1648 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001649 }
Riley Andrews03414a12014-07-01 14:22:59 -07001650
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001651
1652 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1653
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 // Set the per-frame data
1655 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1656 auto& displayDevice = mDisplays[displayId];
1657 const auto hwcId = displayDevice->getHwcDisplayId();
1658 if (hwcId < 0) {
1659 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001660 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001661 if (colorMatrix != mPreviousColorMatrix) {
1662 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1663 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1664 "display %zd: %d", displayId, result);
1665 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1667 layer->setPerFrameData(displayDevice);
1668 }
1669 }
1670
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001671 mPreviousColorMatrix = colorMatrix;
1672
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001674 auto& displayDevice = mDisplays[displayId];
1675 if (!displayDevice->isDisplayOn()) {
1676 continue;
1677 }
1678
1679 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001680 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1681 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001682 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001684
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685void SurfaceFlinger::doComposition() {
1686 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 ALOGV("doComposition");
1688
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001689 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001690 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001691 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001692 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 // transform the dirty region into this screen's coordinate space
1694 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001695
1696 // repaint the framebuffer (if needed)
1697 doDisplayComposition(hw, dirtyRegion);
1698
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 hw->dirtyRegion.clear();
1700 hw->flip(hw->swapRegion);
1701 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001702 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001704 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001705}
1706
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001707void SurfaceFlinger::postFramebuffer()
1708{
Mathias Agopian841cde52012-03-01 15:44:37 -08001709 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001711
Mathias Agopiana44b0412011-10-16 18:46:35 -07001712 const nsecs_t now = systemTime();
1713 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001714
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1716 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001717 if (!displayDevice->isDisplayOn()) {
1718 continue;
1719 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001720 const auto hwcId = displayDevice->getHwcDisplayId();
1721 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001722 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001723 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001724 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001725 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1727 sp<Fence> releaseFence = Fence::NO_FENCE;
1728 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1729 releaseFence = displayDevice->getClientTargetAcquireFence();
1730 } else {
1731 auto hwcLayer = layer->getHwcLayer(hwcId);
1732 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001733 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001734 layer->onLayerDisplayed(releaseFence);
1735 }
1736 if (hwcId >= 0) {
1737 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001738 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001739 }
1740
Mathias Agopiana44b0412011-10-16 18:46:35 -07001741 mLastSwapBufferTime = systemTime() - now;
1742 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001743
1744 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1745 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1746 logFrameStats();
1747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001748}
1749
Mathias Agopian87baae12012-07-31 12:38:26 -07001750void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751{
Mathias Agopian841cde52012-03-01 15:44:37 -08001752 ATRACE_CALL();
1753
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001754 // here we keep a copy of the drawing state (that is the state that's
1755 // going to be overwritten by handleTransactionLocked()) outside of
1756 // mStateLock so that the side-effects of the State assignment
1757 // don't happen with mStateLock held (which can cause deadlocks).
1758 State drawingState(mDrawingState);
1759
Mathias Agopianca4d3602011-05-19 15:38:14 -07001760 Mutex::Autolock _l(mStateLock);
1761 const nsecs_t now = systemTime();
1762 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001763
Mathias Agopianca4d3602011-05-19 15:38:14 -07001764 // Here we're guaranteed that some transaction flags are set
1765 // so we can call handleTransactionLocked() unconditionally.
1766 // We call getTransactionFlags(), which will also clear the flags,
1767 // with mStateLock held to guarantee that mCurrentState won't change
1768 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001769
Mathias Agopiane57f2922012-08-09 16:29:12 -07001770 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001771 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001772
Mathias Agopianca4d3602011-05-19 15:38:14 -07001773 mLastTransactionTime = systemTime() - now;
1774 mDebugInTransaction = 0;
1775 invalidateHwcGeometry();
1776 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001777}
1778
Mathias Agopian87baae12012-07-31 12:38:26 -07001779void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001780{
Dan Stoza7dde5992015-05-22 09:51:44 -07001781 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001782 mCurrentState.traverseInZOrder([](Layer* layer) {
1783 layer->notifyAvailableFrames();
1784 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 /*
1787 * Traversal of the children
1788 * (perform the transaction for each of them if needed)
1789 */
1790
Mathias Agopian3559b072012-08-15 13:46:03 -07001791 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001792 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001793 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001794 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795
1796 const uint32_t flags = layer->doTransaction(0);
1797 if (flags & Layer::eVisibleRegion)
1798 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001799 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001800 }
1801
1802 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001803 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 */
1805
Mathias Agopiane57f2922012-08-09 16:29:12 -07001806 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001807 // here we take advantage of Vector's copy-on-write semantics to
1808 // improve performance by skipping the transaction entirely when
1809 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001810 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1811 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001812 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001814 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001815 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001816
1817 // find the displays that were removed
1818 // (ie: in drawing state but not in current state)
1819 // also handle displays that changed
1820 // (ie: displays that are in both lists)
1821 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001822 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1823 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001824 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001825 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001826 // Call makeCurrent() on the primary display so we can
1827 // be sure that nothing associated with this display
1828 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001829 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001830 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001831 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1832 if (hw != NULL)
1833 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001834 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001835 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001836 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001837 } else {
1838 ALOGW("trying to remove the main display");
1839 }
1840 } else {
1841 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001842 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001843 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001844 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1845 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001846 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001847 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001848 // recreating the DisplayDevice, so we just remove it
1849 // from the drawing state, so that it get re-added
1850 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001851 sp<DisplayDevice> hw(getDisplayDevice(display));
1852 if (hw != NULL)
1853 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001854 mDisplays.removeItem(display);
1855 mDrawingState.displays.removeItemsAt(i);
1856 dc--; i--;
1857 // at this point we must loop to the next item
1858 continue;
1859 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001860
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001861 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001862 if (disp != NULL) {
1863 if (state.layerStack != draw[i].layerStack) {
1864 disp->setLayerStack(state.layerStack);
1865 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001866 if ((state.orientation != draw[i].orientation)
1867 || (state.viewport != draw[i].viewport)
1868 || (state.frame != draw[i].frame))
1869 {
1870 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001871 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001872 }
Michael Lentine47e45402014-07-18 15:34:25 -07001873 if (state.width != draw[i].width || state.height != draw[i].height) {
1874 disp->setDisplaySize(state.width, state.height);
1875 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001876 }
1877 }
1878 }
1879
1880 // find displays that were added
1881 // (ie: in current state but not in drawing state)
1882 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001883 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001884 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001885
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001886 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001887 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001888 sp<IGraphicBufferProducer> bqProducer;
1889 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001890 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001891
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001893 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001894 // Virtual displays without a surface are dormant:
1895 // they have external state (layer stack, projection,
1896 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001897 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001898
Dan Stoza8cf150a2016-08-02 10:27:31 -07001899 if (mUseHwcVirtualDisplays) {
1900 int width = 0;
1901 int status = state.surface->query(
1902 NATIVE_WINDOW_WIDTH, &width);
1903 ALOGE_IF(status != NO_ERROR,
1904 "Unable to query width (%d)", status);
1905 int height = 0;
1906 status = state.surface->query(
1907 NATIVE_WINDOW_HEIGHT, &height);
1908 ALOGE_IF(status != NO_ERROR,
1909 "Unable to query height (%d)", status);
1910 int intFormat = 0;
1911 status = state.surface->query(
1912 NATIVE_WINDOW_FORMAT, &intFormat);
1913 ALOGE_IF(status != NO_ERROR,
1914 "Unable to query format (%d)", status);
1915 auto format = static_cast<android_pixel_format_t>(
1916 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001917
Dan Stoza8cf150a2016-08-02 10:27:31 -07001918 mHwc->allocateVirtualDisplay(width, height, &format,
1919 &hwcId);
1920 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921
Dan Stoza5cf424b2016-05-20 14:02:39 -07001922 // TODO: Plumb requested format back up to consumer
1923
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 sp<VirtualDisplaySurface> vds =
1925 new VirtualDisplaySurface(*mHwc,
1926 hwcId, state.surface, bqProducer,
1927 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001928
1929 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001930 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001931 }
1932 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001933 ALOGE_IF(state.surface!=NULL,
1934 "adding a supported display, but rendering "
1935 "surface is provided (%p), ignoring it",
1936 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001937
1938 hwcId = state.type;
1939 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1940 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001941 }
1942
1943 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001944 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001945 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 state.type, hwcId, state.isSecure, display,
1947 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001948 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001949 hw->setLayerStack(state.layerStack);
1950 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001951 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001952 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001953 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001955 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001956 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001957 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001958 }
1959 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001961 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001962
Mathias Agopian84300952012-11-21 16:02:13 -08001963 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1964 // The transform hint might have changed for some layers
1965 // (either because a display has changed, or because a layer
1966 // as changed).
1967 //
1968 // Walk through all the layers in currentLayers,
1969 // and update their transform hint.
1970 //
1971 // If a layer is visible only on a single display, then that
1972 // display is used to calculate the hint, otherwise we use the
1973 // default display.
1974 //
1975 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1976 // the hint is set before we acquire a buffer from the surface texture.
1977 //
1978 // NOTE: layer transactions have taken place already, so we use their
1979 // drawing state. However, SurfaceFlinger's own transaction has not
1980 // happened yet, so we must use the current state layer list
1981 // (soon to become the drawing state list).
1982 //
1983 sp<const DisplayDevice> disp;
1984 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001985 bool first = true;
1986 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001987 // NOTE: we rely on the fact that layers are sorted by
1988 // layerStack first (so we don't have to traverse the list
1989 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001990 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001991 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001992 currentlayerStack = layerStack;
1993 // figure out if this layerstack is mirrored
1994 // (more than one display) if so, pick the default display,
1995 // if not, pick the only display it's on.
1996 disp.clear();
1997 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1998 sp<const DisplayDevice> hw(mDisplays[dpy]);
1999 if (hw->getLayerStack() == currentlayerStack) {
2000 if (disp == NULL) {
2001 disp = hw;
2002 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002003 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002004 break;
2005 }
2006 }
2007 }
2008 }
Chet Haase91d25932013-04-11 15:24:55 -07002009 if (disp == NULL) {
2010 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2011 // redraw after transform hint changes. See bug 8508397.
2012
2013 // could be null when this layer is using a layerStack
2014 // that is not visible on any display. Also can occur at
2015 // screen off/on times.
2016 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002017 }
Chet Haase91d25932013-04-11 15:24:55 -07002018 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002019
2020 first = false;
2021 });
Mathias Agopian84300952012-11-21 16:02:13 -08002022 }
2023
2024
Mathias Agopian3559b072012-08-15 13:46:03 -07002025 /*
2026 * Perform our own transaction if needed
2027 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002028
2029 if (mLayersAdded) {
2030 mLayersAdded = false;
2031 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002032 mVisibleRegionsDirty = true;
2033 }
2034
2035 // some layers might have been removed, so
2036 // we need to update the regions they're exposing.
2037 if (mLayersRemoved) {
2038 mLayersRemoved = false;
2039 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002040 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002041 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002042 // this layer is not visible anymore
2043 // TODO: we could traverse the tree from front to back and
2044 // compute the actual visible region
2045 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002046 Region visibleReg;
2047 visibleReg.set(layer->computeScreenBounds());
2048 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002049 }
Robert Carr2047fae2016-11-28 14:09:09 -08002050 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051 }
2052
2053 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002054
2055 updateCursorAsync();
2056}
2057
2058void SurfaceFlinger::updateCursorAsync()
2059{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2061 auto& displayDevice = mDisplays[displayId];
2062 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002063 continue;
2064 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065
2066 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2067 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002068 }
2069 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002070}
2071
2072void SurfaceFlinger::commitTransaction()
2073{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002074 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002075 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002076 for (const auto& l : mLayersPendingRemoval) {
2077 recordBufferingStats(l->getName().string(),
2078 l->getOccupancyHistory(true));
2079 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002080 }
2081 mLayersPendingRemoval.clear();
2082 }
2083
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002084 // If this transaction is part of a window animation then the next frame
2085 // we composite should be considered an animation as well.
2086 mAnimCompositionPending = mAnimTransactionPending;
2087
Mathias Agopian4fec8732012-06-29 14:12:52 -07002088 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002089 mDrawingState.traverseInZOrder([](Layer* layer) {
2090 layer->commitChildList();
2091 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002092 mTransactionPending = false;
2093 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095}
2096
Robert Carr2047fae2016-11-28 14:09:09 -08002097void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002098 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099{
Mathias Agopian841cde52012-03-01 15:44:37 -08002100 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103 Region aboveOpaqueLayers;
2104 Region aboveCoveredLayers;
2105 Region dirty;
2106
Mathias Agopian87baae12012-07-31 12:38:26 -07002107 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108
Robert Carr2047fae2016-11-28 14:09:09 -08002109 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002111 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112
Jesse Hall01e29052013-02-19 16:13:35 -08002113 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002114 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002115 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002116
Mathias Agopianab028732010-03-16 16:41:46 -07002117 /*
2118 * opaqueRegion: area of a surface that is fully opaque.
2119 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002121
2122 /*
2123 * visibleRegion: area of a surface that is visible on screen
2124 * and not fully transparent. This is essentially the layer's
2125 * footprint minus the opaque regions above it.
2126 * Areas covered by a translucent surface are considered visible.
2127 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002129
2130 /*
2131 * coveredRegion: area of a surface that is covered by all
2132 * visible regions above it (which includes the translucent areas).
2133 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002135
Jesse Halla8026d22012-09-25 13:25:04 -07002136 /*
2137 * transparentRegion: area of a surface that is hinted to be completely
2138 * transparent. This is only used to tell when the layer has no visible
2139 * non-transparent regions and can be removed from the layer list. It
2140 * does not affect the visibleRegion of this layer or any layers
2141 * beneath it. The hint may not be correct if apps don't respect the
2142 * SurfaceView restrictions (which, sadly, some don't).
2143 */
2144 Region transparentRegion;
2145
Mathias Agopianab028732010-03-16 16:41:46 -07002146
2147 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002148 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002149 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002150 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002152 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002153 if (!visibleRegion.isEmpty()) {
2154 // Remove the transparent area from the visible region
2155 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002156 if (tr.preserveRects()) {
2157 // transform the transparent region
2158 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002159 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002160 // transformation too complex, can't do the
2161 // transparent region optimization.
2162 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002163 }
Mathias Agopianab028732010-03-16 16:41:46 -07002164 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165
Mathias Agopianab028732010-03-16 16:41:46 -07002166 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002167 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002169 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2170 // the opaque region is the layer's footprint
2171 opaqueRegion = visibleRegion;
2172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173 }
2174 }
2175
Mathias Agopianab028732010-03-16 16:41:46 -07002176 // Clip the covered region to the visible region
2177 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2178
2179 // Update aboveCoveredLayers for next (lower) layer
2180 aboveCoveredLayers.orSelf(visibleRegion);
2181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002182 // subtract the opaque region covered by the layers above us
2183 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002184
2185 // compute this layer's dirty region
2186 if (layer->contentDirty) {
2187 // we need to invalidate the whole region
2188 dirty = visibleRegion;
2189 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191 layer->contentDirty = false;
2192 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002193 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002194 * the exposed region consists of two components:
2195 * 1) what's VISIBLE now and was COVERED before
2196 * 2) what's EXPOSED now less what was EXPOSED before
2197 *
2198 * note that (1) is conservative, we start with the whole
2199 * visible region but only keep what used to be covered by
2200 * something -- which mean it may have been exposed.
2201 *
2202 * (2) handles areas that were not covered by anything but got
2203 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002204 */
Mathias Agopianab028732010-03-16 16:41:46 -07002205 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002206 const Region oldVisibleRegion = layer->visibleRegion;
2207 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002208 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2209 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210 }
2211 dirty.subtractSelf(aboveOpaqueLayers);
2212
2213 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002214 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002215
Mathias Agopianab028732010-03-16 16:41:46 -07002216 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002218
Jesse Halla8026d22012-09-25 13:25:04 -07002219 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220 layer->setVisibleRegion(visibleRegion);
2221 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002222 layer->setVisibleNonTransparentRegion(
2223 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002224 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225
Mathias Agopian87baae12012-07-31 12:38:26 -07002226 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002227}
2228
Mathias Agopian87baae12012-07-31 12:38:26 -07002229void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2230 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002231 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002232 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2233 if (hw->getLayerStack() == layerStack) {
2234 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002235 }
2236 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002237}
2238
Dan Stoza6b9454d2014-11-07 16:00:59 -08002239bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 ALOGV("handlePageFlip");
2242
Brian Andersond6927fb2016-07-23 23:37:30 -07002243 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244
Mathias Agopian4fec8732012-06-29 14:12:52 -07002245 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002246 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002247
2248 // Store the set of layers that need updates. This set must not change as
2249 // buffers are being latched, as this could result in a deadlock.
2250 // Example: Two producers share the same command stream and:
2251 // 1.) Layer 0 is latched
2252 // 2.) Layer 0 gets a new frame
2253 // 2.) Layer 1 gets a new frame
2254 // 3.) Layer 1 is latched.
2255 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2256 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002257 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002258 if (layer->hasQueuedFrame()) {
2259 frameQueued = true;
2260 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002261 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002262 } else {
2263 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002264 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002265 } else {
2266 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267 }
Robert Carr2047fae2016-11-28 14:09:09 -08002268 });
2269
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002271 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002272 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002273 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002274 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002275
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002276 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002277
2278 // If we will need to wake up at some time in the future to deal with a
2279 // queued frame that shouldn't be displayed during this vsync period, wake
2280 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002281 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002282 signalLayerUpdate();
2283 }
2284
2285 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002286 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287}
2288
Mathias Agopianad456f92011-01-13 17:53:01 -08002289void SurfaceFlinger::invalidateHwcGeometry()
2290{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002291 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002292}
2293
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002294
Fabien Sanglard830b8472016-11-30 16:35:58 -08002295void SurfaceFlinger::doDisplayComposition(
2296 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002297 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298{
Dan Stoza71433162014-02-04 16:22:36 -08002299 // We only need to actually compose the display if:
2300 // 1) It is being handled by hardware composer, which may need this to
2301 // keep its virtual display state machine in sync, or
2302 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002303 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002304 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002306 return;
2307 }
2308
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 ALOGV("doDisplayComposition");
2310
Mathias Agopian87baae12012-07-31 12:38:26 -07002311 Region dirtyRegion(inDirtyRegion);
2312
Mathias Agopianb8a55602009-06-26 19:06:36 -07002313 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002314 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315
Fabien Sanglard830b8472016-11-30 16:35:58 -08002316 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002317 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002318 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2319 // takes a rectangle, we must make sure to update that whole
2320 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002321 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002322 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002323 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002324 // We need to redraw the rectangle that will be updated
2325 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002326 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002327 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002328 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002329 } else {
2330 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 dirtyRegion.set(displayDevice->bounds());
2332 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 }
2334 }
2335
Fabien Sanglard830b8472016-11-30 16:35:58 -08002336 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002338 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002340
2341 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343}
2344
Dan Stoza9e56aa02015-11-02 13:00:03 -08002345bool SurfaceFlinger::doComposeSurfaces(
2346 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002347{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002349
Dan Stoza9e56aa02015-11-02 13:00:03 -08002350 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002351
2352 mat4 oldColorMatrix;
2353 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2354 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2355 if (applyColorMatrix) {
2356 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2357 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2358 }
2359
Dan Stoza9e56aa02015-11-02 13:00:03 -08002360 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2361 if (hasClientComposition) {
2362 ALOGV("hasClientComposition");
2363
2364 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002365 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002367 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2368 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2369 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2370 }
2371 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002372 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002373
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002374 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2376 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002377 // when using overlays, we assume a fully transparent framebuffer
2378 // NOTE: we could reduce how much we need to clear, for instance
2379 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002380 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002381 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002383 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002384 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002385 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002386
2387 // we remove the scissor part
2388 // we're left with the letterbox region
2389 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002390 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002391
2392 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002394
2395 // but limit it to the dirty region
2396 region.andSelf(dirty);
2397
Mathias Agopianb9494d52012-04-18 02:28:45 -07002398 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002399 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002400 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002402 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002403 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002404
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002406 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002407 // scissor on the main display. It should never be needed
2408 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 const Rect& bounds(displayDevice->getBounds());
2410 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002411 if (scissor != bounds) {
2412 // scissor doesn't match the screen's dimensions, so we
2413 // need to clear everything outside of it and enable
2414 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002415
Mathias Agopianf45c5102012-10-24 16:29:17 -07002416 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 const uint32_t height = displayDevice->getHeight();
2418 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002419 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002420 }
2421 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002422 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002423
Mathias Agopian85d751c2012-08-29 16:59:24 -07002424 /*
2425 * and then, render the layers targeted at the framebuffer
2426 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002427
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 ALOGV("Rendering client layers");
2429 const Transform& displayTransform = displayDevice->getTransform();
2430 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002431 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 bool firstLayer = true;
2433 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2434 const Region clip(dirty.intersect(
2435 displayTransform.transform(layer->visibleRegion)));
2436 ALOGV("Layer: %s", layer->getName().string());
2437 ALOGV(" Composition type: %s",
2438 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002439 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 switch (layer->getCompositionType(hwcId)) {
2441 case HWC2::Composition::Cursor:
2442 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002443 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002445 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2447 layer->isOpaque(state) && (state.alpha == 1.0f)
2448 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002449 // never clear the very first layer since we're
2450 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002451 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002452 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002453 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002454 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 case HWC2::Composition::Client: {
2456 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002457 break;
2458 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002460 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002461 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 } else {
2463 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002464 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002466 }
2467 } else {
2468 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002470 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002472 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002474 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002475 }
2476 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002477
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002478 if (applyColorMatrix) {
2479 getRenderEngine().setupColorTransform(oldColorMatrix);
2480 }
2481
Mathias Agopianf45c5102012-10-24 16:29:17 -07002482 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002484 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485}
2486
Fabien Sanglard830b8472016-11-30 16:35:58 -08002487void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2488 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002489 RenderEngine& engine(getRenderEngine());
2490 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491}
2492
Dan Stoza7d89d062015-04-30 13:29:25 -07002493status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002494 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002495 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002496 const sp<Layer>& lbc,
2497 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002498{
Dan Stoza7d89d062015-04-30 13:29:25 -07002499 // add this layer to the current state list
2500 {
2501 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002502 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002503 return NO_MEMORY;
2504 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002505 if (parent == nullptr) {
2506 mCurrentState.layersSortedByZ.add(lbc);
2507 } else {
2508 parent->addChild(lbc);
2509 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002510 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 mLayersAdded = true;
2512 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002513 }
2514
Mathias Agopian96f08192010-06-02 23:28:45 -07002515 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002516 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002517
Dan Stoza7d89d062015-04-30 13:29:25 -07002518 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002519}
2520
Robert Carr9524cb32017-02-13 11:32:32 -08002521status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002522 Mutex::Autolock _l(mStateLock);
2523
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 const auto& p = layer->getParent();
2525 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2526 mCurrentState.layersSortedByZ.remove(layer);
2527
Robert Carr136e2f62017-02-08 17:54:29 -08002528 // As a matter of normal operation, the LayerCleaner will produce a second
2529 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2530 // so we will succeed in promoting it, but it's already been removed
2531 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2532 // otherwise something has gone wrong and we are leaking the layer.
2533 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2535 layer->getName().string(),
2536 (p != nullptr) ? p->getName().string() : "no-parent");
2537 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002538 } else if (index < 0) {
2539 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002540 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002541
2542 mLayersPendingRemoval.add(layer);
2543 mLayersRemoved = true;
2544 mNumLayers--;
2545 setTransactionFlags(eTransactionNeeded);
2546 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547}
2548
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002549uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002550 return android_atomic_release_load(&mTransactionFlags);
2551}
2552
Mathias Agopian3f844832013-08-07 21:24:32 -07002553uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2555}
2556
Mathias Agopian3f844832013-08-07 21:24:32 -07002557uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2559 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002560 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 }
2562 return old;
2563}
2564
Mathias Agopian8b33f032012-07-24 20:43:54 -07002565void SurfaceFlinger::setTransactionState(
2566 const Vector<ComposerState>& state,
2567 const Vector<DisplayState>& displays,
2568 uint32_t flags)
2569{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002570 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002571 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002572 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002573
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002574 if (flags & eAnimation) {
2575 // For window updates that are part of an animation we must wait for
2576 // previous animation "frames" to be handled.
2577 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002578 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002579 if (CC_UNLIKELY(err != NO_ERROR)) {
2580 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002581 // caller after a few seconds.
2582 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2583 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002584 mAnimTransactionPending = false;
2585 break;
2586 }
2587 }
2588 }
2589
Mathias Agopiane57f2922012-08-09 16:29:12 -07002590 size_t count = displays.size();
2591 for (size_t i=0 ; i<count ; i++) {
2592 const DisplayState& s(displays[i]);
2593 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002594 }
2595
Mathias Agopiane57f2922012-08-09 16:29:12 -07002596 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002597 for (size_t i=0 ; i<count ; i++) {
2598 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002599 // Here we need to check that the interface we're given is indeed
2600 // one of our own. A malicious client could give us a NULL
2601 // IInterface, or one of its own or even one of our own but a
2602 // different type. All these situations would cause us to crash.
2603 //
2604 // NOTE: it would be better to use RTTI as we could directly check
2605 // that we have a Client*. however, RTTI is disabled in Android.
2606 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002607 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002608 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002609 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002610 sp<Client> client( static_cast<Client *>(s.client.get()) );
2611 transactionFlags |= setClientStateLocked(client, s.state);
2612 }
2613 }
2614 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002615 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002616
Robert Carr2a7dbb42016-05-24 11:41:28 -07002617 // If a synchronous transaction is explicitly requested without any changes,
2618 // force a transaction anyway. This can be used as a flush mechanism for
2619 // previous async transactions.
2620 if (transactionFlags == 0 && (flags & eSynchronous)) {
2621 transactionFlags = eTransactionNeeded;
2622 }
2623
Mathias Agopian386aa982011-11-07 21:58:03 -08002624 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002625 if (mInterceptor.isEnabled()) {
2626 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2627 }
Irvel468051e2016-06-13 16:44:44 -07002628
Mathias Agopian386aa982011-11-07 21:58:03 -08002629 // this triggers the transaction
2630 setTransactionFlags(transactionFlags);
2631
2632 // if this is a synchronous transaction, wait for it to take effect
2633 // before returning.
2634 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002635 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002636 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002637 if (flags & eAnimation) {
2638 mAnimTransactionPending = true;
2639 }
2640 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002641 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2642 if (CC_UNLIKELY(err != NO_ERROR)) {
2643 // just in case something goes wrong in SF, return to the
2644 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002645 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2646 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002647 break;
2648 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 }
2651}
2652
Mathias Agopiane57f2922012-08-09 16:29:12 -07002653uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2654{
Jesse Hall9a143922012-10-04 16:29:19 -07002655 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2656 if (dpyIdx < 0)
2657 return 0;
2658
Mathias Agopiane57f2922012-08-09 16:29:12 -07002659 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002660 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002661 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002662 const uint32_t what = s.what;
2663 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002664 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002665 disp.surface = s.surface;
2666 flags |= eDisplayTransactionNeeded;
2667 }
2668 }
2669 if (what & DisplayState::eLayerStackChanged) {
2670 if (disp.layerStack != s.layerStack) {
2671 disp.layerStack = s.layerStack;
2672 flags |= eDisplayTransactionNeeded;
2673 }
2674 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002675 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676 if (disp.orientation != s.orientation) {
2677 disp.orientation = s.orientation;
2678 flags |= eDisplayTransactionNeeded;
2679 }
2680 if (disp.frame != s.frame) {
2681 disp.frame = s.frame;
2682 flags |= eDisplayTransactionNeeded;
2683 }
2684 if (disp.viewport != s.viewport) {
2685 disp.viewport = s.viewport;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 }
Michael Lentine47e45402014-07-18 15:34:25 -07002689 if (what & DisplayState::eDisplaySizeChanged) {
2690 if (disp.width != s.width) {
2691 disp.width = s.width;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 if (disp.height != s.height) {
2695 disp.height = s.height;
2696 flags |= eDisplayTransactionNeeded;
2697 }
2698 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002699 }
2700 return flags;
2701}
2702
2703uint32_t SurfaceFlinger::setClientStateLocked(
2704 const sp<Client>& client,
2705 const layer_state_t& s)
2706{
2707 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002708 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002709 if (layer != 0) {
2710 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002711 bool geometryAppliesWithResize =
2712 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002714 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002716 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002717 }
2718 if (what & layer_state_t::eLayerChanged) {
2719 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 const auto& p = layer->getParent();
2721 if (p == nullptr) {
2722 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2723 if (layer->setLayer(s.z) && idx >= 0) {
2724 mCurrentState.layersSortedByZ.removeAt(idx);
2725 mCurrentState.layersSortedByZ.add(layer);
2726 // we need traversal (state changed)
2727 // AND transaction (list changed)
2728 flags |= eTransactionNeeded|eTraversalNeeded;
2729 }
2730 } else {
2731 if (p->setChildLayer(layer, s.z)) {
2732 flags |= eTransactionNeeded|eTraversalNeeded;
2733 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002734 }
2735 }
2736 if (what & layer_state_t::eSizeChanged) {
2737 if (layer->setSize(s.w, s.h)) {
2738 flags |= eTraversalNeeded;
2739 }
2740 }
2741 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 flags |= eTraversalNeeded;
2744 }
2745 if (what & layer_state_t::eMatrixChanged) {
2746 if (layer->setMatrix(s.matrix))
2747 flags |= eTraversalNeeded;
2748 }
2749 if (what & layer_state_t::eTransparentRegionChanged) {
2750 if (layer->setTransparentRegionHint(s.transparentRegion))
2751 flags |= eTraversalNeeded;
2752 }
Dan Stoza23116082015-06-18 14:58:39 -07002753 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002754 if (layer->setFlags(s.flags, s.mask))
2755 flags |= eTraversalNeeded;
2756 }
2757 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002758 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759 flags |= eTraversalNeeded;
2760 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002761 if (what & layer_state_t::eFinalCropChanged) {
2762 if (layer->setFinalCrop(s.finalCrop))
2763 flags |= eTraversalNeeded;
2764 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002765 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002766 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 // We only allow setting layer stacks for top level layers,
2768 // everything else inherits layer stack from its parent.
2769 if (layer->hasParent()) {
2770 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2771 layer->getName().string());
2772 } else if (idx < 0) {
2773 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2774 "that also does not appear in the top level layer list. Something"
2775 " has gone wrong.", layer->getName().string());
2776 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002777 mCurrentState.layersSortedByZ.removeAt(idx);
2778 mCurrentState.layersSortedByZ.add(layer);
2779 // we need traversal (state changed)
2780 // AND transaction (list changed)
2781 flags |= eTransactionNeeded|eTraversalNeeded;
2782 }
2783 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002784 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002785 if (s.barrierHandle != nullptr) {
2786 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2787 } else if (s.barrierGbp != nullptr) {
2788 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2789 if (authenticateSurfaceTextureLocked(gbp)) {
2790 const auto& otherLayer =
2791 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2792 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2793 } else {
2794 ALOGE("Attempt to defer transaction to to an"
2795 " unrecognized GraphicBufferProducer");
2796 }
2797 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002798 // We don't trigger a traversal here because if no other state is
2799 // changed, we don't want this to cause any more work
2800 }
Robert Carr1db73f62016-12-21 12:58:51 -08002801 if (what & layer_state_t::eReparentChildren) {
2802 if (layer->reparentChildren(s.reparentHandle)) {
2803 flags |= eTransactionNeeded|eTraversalNeeded;
2804 }
2805 }
Robert Carr9524cb32017-02-13 11:32:32 -08002806 if (what & layer_state_t::eDetachChildren) {
2807 layer->detachChildren();
2808 }
Robert Carrc3574f72016-03-24 12:19:32 -07002809 if (what & layer_state_t::eOverrideScalingModeChanged) {
2810 layer->setOverrideScalingMode(s.overrideScalingMode);
2811 // We don't trigger a traversal here because if no other state is
2812 // changed, we don't want this to cause any more work
2813 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002814 }
2815 return flags;
2816}
2817
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002818status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002819 const String8& name,
2820 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002821 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002822 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2823 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002825 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002826 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002827 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002828 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002829 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002830
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002831 status_t result = NO_ERROR;
2832
2833 sp<Layer> layer;
2834
Mathias Agopian3165cc22012-08-08 19:42:09 -07002835 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2836 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002837 result = createNormalLayer(client,
2838 name, w, h, flags, format,
2839 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002841 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002842 result = createDimLayer(client,
2843 name, w, h, flags,
2844 handle, gbp, &layer);
2845 break;
2846 default:
2847 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 break;
2849 }
2850
Dan Stoza7d89d062015-04-30 13:29:25 -07002851 if (result != NO_ERROR) {
2852 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002854
Albert Chaulk479c60c2017-01-27 14:21:34 -05002855 layer->setInfo(windowType, ownerUid);
2856
Robert Carr1f0a16a2016-10-24 16:27:39 -07002857 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002858 if (result != NO_ERROR) {
2859 return result;
2860 }
Irvelffc9efc2016-07-27 15:16:37 -07002861 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002862
2863 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002864 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002867status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2868 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2869 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870{
2871 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002872 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 case PIXEL_FORMAT_TRANSPARENT:
2874 case PIXEL_FORMAT_TRANSLUCENT:
2875 format = PIXEL_FORMAT_RGBA_8888;
2876 break;
2877 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002878 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 break;
2880 }
2881
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002882 *outLayer = new Layer(this, client, name, w, h, flags);
2883 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2884 if (err == NO_ERROR) {
2885 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002886 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002888
2889 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2890 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2894 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2895 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002897 *outLayer = new LayerDim(this, client, name, w, h, flags);
2898 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002899 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002900 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002901}
2902
Mathias Agopianac9fa422013-02-11 16:40:36 -08002903status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904{
Robert Carr9524cb32017-02-13 11:32:32 -08002905 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002906 status_t err = NO_ERROR;
2907 sp<Layer> l(client->getLayerUser(handle));
2908 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002909 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002910 err = removeLayer(l);
2911 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2912 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002913 }
2914 return err;
2915}
2916
Mathias Agopian13127d82013-03-05 17:47:11 -08002917status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002918{
Mathias Agopian67106042013-03-14 19:18:13 -07002919 // called by ~LayerCleaner() when all references to the IBinder (handle)
2920 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002921 sp<Layer> l = layer.promote();
2922 if (l == nullptr) {
2923 // The layer has already been removed, carry on
2924 return NO_ERROR;
2925 } if (l->getParent() != nullptr) {
2926 // If we have a parent, then we can continue to live as long as it does.
2927 return NO_ERROR;
2928 }
2929 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Mathias Agopianb60314a2012-04-10 22:09:54 -07002932// ---------------------------------------------------------------------------
2933
Andy McFadden13a082e2012-08-24 10:16:42 -07002934void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002935 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002936 Vector<ComposerState> state;
2937 Vector<DisplayState> displays;
2938 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002939 d.what = DisplayState::eDisplayProjectionChanged |
2940 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002941 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002942 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002943 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002944 d.frame.makeInvalid();
2945 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002946 d.width = 0;
2947 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002948 displays.add(d);
2949 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002950 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002951
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2953 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002954 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002955
2956 {
2957 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2958 mCompositorTiming.interval = period;
2959 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002960}
2961
2962void SurfaceFlinger::initializeDisplays() {
2963 class MessageScreenInitialized : public MessageBase {
2964 SurfaceFlinger* flinger;
2965 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002966 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002967 virtual bool handler() {
2968 flinger->onInitializeDisplays();
2969 return true;
2970 }
2971 };
2972 sp<MessageBase> msg = new MessageScreenInitialized(this);
2973 postMessageAsync(msg); // we may be called from main thread, use async message
2974}
2975
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2977 int mode) {
2978 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2979 this);
2980 int32_t type = hw->getDisplayType();
2981 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002982
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002983 if (mode == currentMode) {
2984 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002985 return;
2986 }
2987
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002988 hw->setPowerMode(mode);
2989 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2990 ALOGW("Trying to set power mode for virtual display");
2991 return;
2992 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002993
Irvelffc9efc2016-07-27 15:16:37 -07002994 if (mInterceptor.isEnabled()) {
2995 Mutex::Autolock _l(mStateLock);
2996 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2997 if (idx < 0) {
2998 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2999 return;
3000 }
3001 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3002 }
3003
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003004 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003005 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003007 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3008 // FIXME: eventthread only knows about the main display right now
3009 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003010 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003013 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003014 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003016
3017 struct sched_param param = {0};
3018 param.sched_priority = 1;
3019 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3020 ALOGW("Couldn't set SCHED_FIFO on display on");
3021 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003022 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003023 // Turn off the display
3024 struct sched_param param = {0};
3025 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3026 ALOGW("Couldn't set SCHED_OTHER on display off");
3027 }
3028
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003029 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003030 disableHardwareVsync(true); // also cancels any in-progress resync
3031
Mathias Agopiancde87a32012-09-13 14:09:01 -07003032 // FIXME: eventthread only knows about the main display right now
3033 mEventThread->onScreenReleased();
3034 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003035
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003036 getHwComposer().setPowerMode(type, mode);
3037 mVisibleRegionsDirty = true;
3038 // from this point on, SF will stop drawing on this display
3039 } else {
3040 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003041 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003042}
3043
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3045 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003046 SurfaceFlinger& mFlinger;
3047 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003049 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003050 MessageSetPowerMode(SurfaceFlinger& flinger,
3051 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3052 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003053 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003054 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003055 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003056 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003057 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003058 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003059 ALOGW("Attempt to set power mode = %d for virtual display",
3060 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003061 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003062 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003063 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003064 return true;
3065 }
3066 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003067 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003068 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003069}
3070
3071// ---------------------------------------------------------------------------
3072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3074{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003076
Mathias Agopianbd115332013-04-18 16:41:04 -07003077 IPCThreadState* ipc = IPCThreadState::self();
3078 const int pid = ipc->getCallingPid();
3079 const int uid = ipc->getCallingUid();
3080 if ((uid != AID_SHELL) &&
3081 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003082 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003083 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003085 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003086 // (this would indicate SF is stuck, but we want to be able to
3087 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003088 status_t err = mStateLock.timedLock(s2ns(1));
3089 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003090 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003091 result.appendFormat(
3092 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3093 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003094 }
3095
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003096 bool dumpAll = true;
3097 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003098 size_t numArgs = args.size();
3099 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003100 if ((index < numArgs) &&
3101 (args[index] == String16("--list"))) {
3102 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003104 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003105 }
3106
3107 if ((index < numArgs) &&
3108 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003109 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003111 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003112 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003113
3114 if ((index < numArgs) &&
3115 (args[index] == String16("--latency-clear"))) {
3116 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003117 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003118 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003119 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--dispsync"))) {
3123 index++;
3124 mPrimaryDispSync.dump(result);
3125 dumpAll = false;
3126 }
Dan Stozab90cf072015-03-05 11:05:59 -08003127
3128 if ((index < numArgs) &&
3129 (args[index] == String16("--static-screen"))) {
3130 index++;
3131 dumpStaticScreenStats(result);
3132 dumpAll = false;
3133 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003134
3135 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003136 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003137 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003138 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003139 dumpAll = false;
3140 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003142
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003143 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003144 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003145 }
3146
Mathias Agopian9795c422009-08-26 16:36:26 -07003147 if (locked) {
3148 mStateLock.unlock();
3149 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 }
3151 write(fd, result.string(), result.size());
3152 return NO_ERROR;
3153}
3154
Dan Stozac7014012014-02-14 15:03:43 -08003155void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3156 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003157{
Robert Carr2047fae2016-11-28 14:09:09 -08003158 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003159 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003160 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003161}
3162
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003163void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003164 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003165{
3166 String8 name;
3167 if (index < args.size()) {
3168 name = String8(args[index]);
3169 index++;
3170 }
3171
Dan Stoza9e56aa02015-11-02 13:00:03 -08003172 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3173 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003174 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003175
3176 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003177 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003178 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003179 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003180 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003181 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003182 }
Robert Carr2047fae2016-11-28 14:09:09 -08003183 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003184 }
3185}
3186
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003187void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003188 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003189{
3190 String8 name;
3191 if (index < args.size()) {
3192 name = String8(args[index]);
3193 index++;
3194 }
3195
Robert Carr2047fae2016-11-28 14:09:09 -08003196 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003197 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003198 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003199 }
Robert Carr2047fae2016-11-28 14:09:09 -08003200 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003201
Svetoslavd85084b2014-03-20 10:28:31 -07003202 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003203}
3204
Jamie Gennis6547ff42013-07-16 20:12:42 -07003205// This should only be called from the main thread. Otherwise it would need
3206// the lock and should use mCurrentState rather than mDrawingState.
3207void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003208 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003209 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003210 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003211
3212 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3213}
3214
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003215void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003216{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003218#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003220#endif
3221#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003222 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003223#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003224 if (isLayerTripleBufferingDisabled())
3225 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003226 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003227}
3228
Dan Stozab90cf072015-03-05 11:05:59 -08003229void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3230{
3231 result.appendFormat("Static screen stats:\n");
3232 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3233 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3234 float percent = 100.0f *
3235 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3236 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3237 b + 1, bucketTimeSec, percent);
3238 }
3239 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3240 float percent = 100.0f *
3241 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3242 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3243 NUM_BUCKETS - 1, bucketTimeSec, percent);
3244}
3245
Dan Stozae77c7662016-05-13 11:37:28 -07003246void SurfaceFlinger::recordBufferingStats(const char* layerName,
3247 std::vector<OccupancyTracker::Segment>&& history) {
3248 Mutex::Autolock lock(mBufferingStatsMutex);
3249 auto& stats = mBufferingStats[layerName];
3250 for (const auto& segment : history) {
3251 if (!segment.usedThirdBuffer) {
3252 stats.twoBufferTime += segment.totalTime;
3253 }
3254 if (segment.occupancyAverage < 1.0f) {
3255 stats.doubleBufferedTime += segment.totalTime;
3256 } else if (segment.occupancyAverage < 2.0f) {
3257 stats.tripleBufferedTime += segment.totalTime;
3258 }
3259 ++stats.numSegments;
3260 stats.totalTime += segment.totalTime;
3261 }
3262}
3263
Brian Andersond6927fb2016-07-23 23:37:30 -07003264void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3265 result.appendFormat("Layer frame timestamps:\n");
3266
3267 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3268 const size_t count = currentLayers.size();
3269 for (size_t i=0 ; i<count ; i++) {
3270 currentLayers[i]->dumpFrameEvents(result);
3271 }
3272}
3273
Dan Stozae77c7662016-05-13 11:37:28 -07003274void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3275 result.append("Buffering stats:\n");
3276 result.append(" [Layer name] <Active time> <Two buffer> "
3277 "<Double buffered> <Triple buffered>\n");
3278 Mutex::Autolock lock(mBufferingStatsMutex);
3279 typedef std::tuple<std::string, float, float, float> BufferTuple;
3280 std::map<float, BufferTuple, std::greater<float>> sorted;
3281 for (const auto& statsPair : mBufferingStats) {
3282 const char* name = statsPair.first.c_str();
3283 const BufferingStats& stats = statsPair.second;
3284 if (stats.numSegments == 0) {
3285 continue;
3286 }
3287 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3288 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3289 stats.totalTime;
3290 float doubleBufferRatio = static_cast<float>(
3291 stats.doubleBufferedTime) / stats.totalTime;
3292 float tripleBufferRatio = static_cast<float>(
3293 stats.tripleBufferedTime) / stats.totalTime;
3294 sorted.insert({activeTime, {name, twoBufferRatio,
3295 doubleBufferRatio, tripleBufferRatio}});
3296 }
3297 for (const auto& sortedPair : sorted) {
3298 float activeTime = sortedPair.first;
3299 const BufferTuple& values = sortedPair.second;
3300 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3301 std::get<0>(values).c_str(), activeTime,
3302 std::get<1>(values), std::get<2>(values),
3303 std::get<3>(values));
3304 }
3305 result.append("\n");
3306}
3307
3308
Mathias Agopian74d211a2013-04-22 16:55:35 +02003309void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3310 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003311{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003312 bool colorize = false;
3313 if (index < args.size()
3314 && (args[index] == String16("--color"))) {
3315 colorize = true;
3316 index++;
3317 }
3318
3319 Colorizer colorizer(colorize);
3320
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003321 // figure out if we're stuck somewhere
3322 const nsecs_t now = systemTime();
3323 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3324 const nsecs_t inTransaction(mDebugInTransaction);
3325 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3326 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3327
3328 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003329 * Dump library configuration.
3330 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003331
3332 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003333 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003334 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003335 appendSfConfigString(result);
3336 appendUiConfigString(result);
3337 appendGuiConfigString(result);
3338 result.append("\n");
3339
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003340 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003341 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003342 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003343 result.append(SyncFeatures::getInstance().toString());
3344 result.append("\n");
3345
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3347
Andy McFadden41d67d72014-04-25 16:58:34 -07003348 colorizer.bold(result);
3349 result.append("DispSync configuration: ");
3350 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003351 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3352 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003353 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3354 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003355 result.append("\n");
3356
Dan Stozab90cf072015-03-05 11:05:59 -08003357 // Dump static screen stats
3358 result.append("\n");
3359 dumpStaticScreenStats(result);
3360 result.append("\n");
3361
Dan Stozae77c7662016-05-13 11:37:28 -07003362 dumpBufferingStats(result);
3363
Andy McFadden4803b742012-09-24 19:07:20 -07003364 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003365 * Dump the visible layer list
3366 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003367 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003368 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003369 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003370 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003371 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003372 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003373
3374 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003375 * Dump Display state
3376 */
3377
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003378 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003379 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003380 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003381 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3382 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003383 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003384 }
3385
3386 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003387 * Dump SurfaceFlinger global state
3388 */
3389
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003390 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003391 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003392 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003393
Mathias Agopian888c8222012-08-04 21:10:38 -07003394 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003395 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003396
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 colorizer.bold(result);
3398 result.appendFormat("EGL implementation : %s\n",
3399 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3400 colorizer.reset(result);
3401 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003402 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003403
Mathias Agopian875d8e12013-06-07 15:35:48 -07003404 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405
Mathias Agopian42977342012-08-05 00:40:46 -07003406 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003407 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3408 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003409 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003410 " last eglSwapBuffers() time: %f us\n"
3411 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003412 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413 " refresh-rate : %f fps\n"
3414 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003415 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003416 " gpu_to_cpu_unsupported : %d\n"
3417 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418 mLastSwapBufferTime/1000.0,
3419 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003420 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003421 1e9 / activeConfig->getVsyncPeriod(),
3422 activeConfig->getDpiX(),
3423 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003424 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425
Mathias Agopian74d211a2013-04-22 16:55:35 +02003426 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003427 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428
Mathias Agopian74d211a2013-04-22 16:55:35 +02003429 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431
3432 /*
3433 * VSYNC state
3434 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003435 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003436 result.append("\n");
3437
3438 /*
3439 * HWC layer minidump
3440 */
3441 for (size_t d = 0; d < mDisplays.size(); d++) {
3442 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3443 int32_t hwcId = displayDevice->getHwcDisplayId();
3444 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3445 continue;
3446 }
3447
3448 result.appendFormat("Display %d HWC layers:\n", hwcId);
3449 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003451 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003452 });
Dan Stozae22aec72016-08-01 13:20:59 -07003453 result.append("\n");
3454 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003455
3456 /*
3457 * Dump HWComposer state
3458 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003459 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003460 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003461 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003462 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003463 result.appendFormat(" h/w composer %s\n",
3464 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003465 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003466
3467 /*
3468 * Dump gralloc state
3469 */
3470 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3471 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003472}
3473
Mathias Agopian13127d82013-03-05 17:47:11 -08003474const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003475SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003476 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003477 wp<IBinder> dpy;
3478 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3479 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3480 dpy = mDisplays.keyAt(i);
3481 break;
3482 }
3483 }
3484 if (dpy == NULL) {
3485 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3486 // Just use the primary display so we have something to return
3487 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3488 }
3489 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003490}
3491
Keun young Park63f165f2012-08-31 10:53:36 -07003492bool SurfaceFlinger::startDdmConnection()
3493{
3494 void* libddmconnection_dso =
3495 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3496 if (!libddmconnection_dso) {
3497 return false;
3498 }
3499 void (*DdmConnection_start)(const char* name);
3500 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003501 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003502 if (!DdmConnection_start) {
3503 dlclose(libddmconnection_dso);
3504 return false;
3505 }
3506 (*DdmConnection_start)(getServiceName());
3507 return true;
3508}
3509
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003510status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 switch (code) {
3512 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003513 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003515 case CLEAR_ANIMATION_FRAME_STATS:
3516 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003517 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003518 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 {
3520 // codes that require permission check
3521 IPCThreadState* ipc = IPCThreadState::self();
3522 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003523 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003524 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003525 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003526 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003527 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003529 break;
3530 }
Robert Carr1db73f62016-12-21 12:58:51 -08003531 /*
3532 * Calling setTransactionState is safe, because you need to have been
3533 * granted a reference to Client* and Handle* to do anything with it.
3534 *
3535 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3536 */
3537 case SET_TRANSACTION_STATE:
3538 case CREATE_SCOPED_CONNECTION:
3539 {
3540 return OK;
3541 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003542 case CAPTURE_SCREEN:
3543 {
3544 // codes that require permission check
3545 IPCThreadState* ipc = IPCThreadState::self();
3546 const int pid = ipc->getCallingPid();
3547 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003548 if ((uid != AID_GRAPHICS) &&
3549 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003550 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003551 return PERMISSION_DENIED;
3552 }
3553 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 }
3555 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003556 return OK;
3557}
3558
3559status_t SurfaceFlinger::onTransact(
3560 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3561{
3562 status_t credentialCheck = CheckTransactCodeCredentials(code);
3563 if (credentialCheck != OK) {
3564 return credentialCheck;
3565 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003566
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3568 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003569 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003570 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003571 IPCThreadState* ipc = IPCThreadState::self();
3572 const int pid = ipc->getCallingPid();
3573 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003574 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003575 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 return PERMISSION_DENIED;
3577 }
3578 int n;
3579 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003580 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003581 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 return NO_ERROR;
3583 case 1002: // SHOW_UPDATES
3584 n = data.readInt32();
3585 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003586 invalidateHwcGeometry();
3587 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003590 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003593 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594 setTransactionFlags(
3595 eTransactionNeeded|
3596 eDisplayTransactionNeeded|
3597 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003598 return NO_ERROR;
3599 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003600 case 1006:{ // send empty update
3601 signalRefresh();
3602 return NO_ERROR;
3603 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003604 case 1008: // toggle use of hw composer
3605 n = data.readInt32();
3606 mDebugDisableHWC = n ? 1 : 0;
3607 invalidateHwcGeometry();
3608 repaintEverything();
3609 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003610 case 1009: // toggle use of transform hint
3611 n = data.readInt32();
3612 mDebugDisableTransformHint = n ? 1 : 0;
3613 invalidateHwcGeometry();
3614 repaintEverything();
3615 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003617 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 reply->writeInt32(0);
3619 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003620 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003621 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 return NO_ERROR;
3623 case 1013: {
3624 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003625 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3626 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003627 return NO_ERROR;
3628 }
3629 case 1014: {
3630 // daltonize
3631 n = data.readInt32();
3632 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003633 case 1:
3634 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3635 break;
3636 case 2:
3637 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3638 break;
3639 case 3:
3640 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3641 break;
3642 default:
3643 mDaltonizer.setType(ColorBlindnessType::None);
3644 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003645 }
3646 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003647 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003648 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003649 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003650 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003651 invalidateHwcGeometry();
3652 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003653 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003655 case 1015: {
3656 // apply a color matrix
3657 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003658 if (n) {
3659 // color matrix is sent as mat3 matrix followed by vec3
3660 // offset, then packed into a mat4 where the last row is
3661 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003662 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003663 for (size_t j = 0; j < 4; j++) {
3664 mColorMatrix[i][j] = data.readFloat();
3665 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003666 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003667 } else {
3668 mColorMatrix = mat4();
3669 }
3670 invalidateHwcGeometry();
3671 repaintEverything();
3672 return NO_ERROR;
3673 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003674 // This is an experimental interface
3675 // Needs to be shifted to proper binder interface when we productize
3676 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003677 n = data.readInt32();
3678 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003679 return NO_ERROR;
3680 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003681 case 1017: {
3682 n = data.readInt32();
3683 mForceFullDamage = static_cast<bool>(n);
3684 return NO_ERROR;
3685 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003686 case 1018: { // Modify Choreographer's phase offset
3687 n = data.readInt32();
3688 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3689 return NO_ERROR;
3690 }
3691 case 1019: { // Modify SurfaceFlinger's phase offset
3692 n = data.readInt32();
3693 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3694 return NO_ERROR;
3695 }
Irvel468051e2016-06-13 16:44:44 -07003696 case 1020: { // Layer updates interceptor
3697 n = data.readInt32();
3698 if (n) {
3699 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003700 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003701 }
3702 else{
3703 ALOGV("Interceptor disabled");
3704 mInterceptor.disable();
3705 }
3706 return NO_ERROR;
3707 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003708 case 1021: { // Disable HWC virtual displays
3709 n = data.readInt32();
3710 mUseHwcVirtualDisplays = !n;
3711 return NO_ERROR;
3712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 }
3714 }
3715 return err;
3716}
3717
Mathias Agopian53331da2011-08-22 21:44:41 -07003718void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003719 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003720 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003721}
3722
Mathias Agopian59119e62010-10-11 12:37:43 -07003723// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003724// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003725// ---------------------------------------------------------------------------
3726
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003727/* The code below is here to handle b/8734824
3728 *
3729 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003730 * from the surfaceflinger thread to the calling binder thread, where they
3731 * are executed. This allows the calling thread in the calling process to be
3732 * reused and not depend on having "enough" binder threads to handle the
3733 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003734 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003735class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003736 /* Parts of GraphicProducerWrapper are run on two different threads,
3737 * communicating by sending messages via Looper but also by shared member
3738 * data. Coherence maintenance is subtle and in places implicit (ugh).
3739 *
3740 * Don't rely on Looper's sendMessage/handleMessage providing
3741 * release/acquire semantics for any data not actually in the Message.
3742 * Data going from surfaceflinger to binder threads needs to be
3743 * synchronized explicitly.
3744 *
3745 * Barrier open/wait do provide release/acquire semantics. This provides
3746 * implicit synchronization for data coming back from binder to
3747 * surfaceflinger threads.
3748 */
3749
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003750 sp<IGraphicBufferProducer> impl;
3751 sp<Looper> looper;
3752 status_t result;
3753 bool exitPending;
3754 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003755 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003756 uint32_t code;
3757 Parcel const* data;
3758 Parcel* reply;
3759
3760 enum {
3761 MSG_API_CALL,
3762 MSG_EXIT
3763 };
3764
3765 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003766 * Called on surfaceflinger thread. This is called by our "fake"
3767 * BpGraphicBufferProducer. We package the data and reply Parcel and
3768 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003769 */
3770 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003771 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003772 this->code = code;
3773 this->data = &data;
3774 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003775 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003776 // if we've exited, we run the message synchronously right here.
3777 // note (JH): as far as I can tell from looking at the code, this
3778 // never actually happens. if it does, i'm not sure if it happens
3779 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003780 handleMessage(Message(MSG_API_CALL));
3781 } else {
3782 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003783 // Prevent stores to this->{code, data, reply} from being
3784 // reordered later than the construction of Message.
3785 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003786 looper->sendMessage(this, Message(MSG_API_CALL));
3787 barrier.wait();
3788 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003789 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003790 }
3791
3792 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003793 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003794 * call the real BpGraphicBufferProducer.
3795 */
3796 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003797 int what = message.what;
3798 // Prevent reads below from happening before the read from Message
3799 atomic_thread_fence(memory_order_acquire);
3800 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003801 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003802 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003803 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003804 exitRequested = true;
3805 }
3806 }
3807
3808public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003809 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003810 : impl(impl),
3811 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003812 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003813 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003814 exitRequested(false),
3815 code(0),
3816 data(NULL),
3817 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003818 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003819
Jesse Hallb154c422014-07-13 12:47:02 -07003820 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003821 status_t waitForResponse() {
3822 do {
3823 looper->pollOnce(-1);
3824 } while (!exitRequested);
3825 return result;
3826 }
3827
Jesse Hallb154c422014-07-13 12:47:02 -07003828 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003830 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003831 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003832 // Ensure this->result is visible to the binder thread before it
3833 // handles the message.
3834 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003835 looper->sendMessage(this, Message(MSG_EXIT));
3836 }
3837};
3838
3839
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003840status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3841 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003842 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003843 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003844 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003845
3846 if (CC_UNLIKELY(display == 0))
3847 return BAD_VALUE;
3848
3849 if (CC_UNLIKELY(producer == 0))
3850 return BAD_VALUE;
3851
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003852 // if we have secure windows on this display, never allow the screen capture
3853 // unless the producer interface is local (i.e.: we can take a screenshot for
3854 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003855 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003856
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003857 // Convert to surfaceflinger's internal rotation type.
3858 Transform::orientation_flags rotationFlags;
3859 switch (rotation) {
3860 case ISurfaceComposer::eRotateNone:
3861 rotationFlags = Transform::ROT_0;
3862 break;
3863 case ISurfaceComposer::eRotate90:
3864 rotationFlags = Transform::ROT_90;
3865 break;
3866 case ISurfaceComposer::eRotate180:
3867 rotationFlags = Transform::ROT_180;
3868 break;
3869 case ISurfaceComposer::eRotate270:
3870 rotationFlags = Transform::ROT_270;
3871 break;
3872 default:
3873 rotationFlags = Transform::ROT_0;
3874 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3875 break;
3876 }
3877
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003878 class MessageCaptureScreen : public MessageBase {
3879 SurfaceFlinger* flinger;
3880 sp<IBinder> display;
3881 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003882 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003883 uint32_t reqWidth, reqHeight;
3884 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003885 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003886 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003887 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003888 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003889 public:
3890 MessageCaptureScreen(SurfaceFlinger* flinger,
3891 const sp<IBinder>& display,
3892 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003893 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003894 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003895 bool useIdentityTransform,
3896 Transform::orientation_flags rotation,
3897 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003898 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003899 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003900 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003901 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003902 rotation(rotation), result(PERMISSION_DENIED),
3903 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003904 {
3905 }
3906 status_t getResult() const {
3907 return result;
3908 }
3909 virtual bool handler() {
3910 Mutex::Autolock _l(flinger->mStateLock);
3911 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003912 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003913 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003914 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003915 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003916 return true;
3917 }
3918 };
3919
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003920 // this creates a "fake" BBinder which will serve as a "fake" remote
3921 // binder to receive the marshaled calls and forward them to the
3922 // real remote (a BpGraphicBufferProducer)
3923 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3924
3925 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3926 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003927 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003928 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003929 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003930 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003931
3932 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003933 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003934 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003935 }
3936 return res;
3937}
3938
Mathias Agopian180f10d2013-04-10 22:55:41 -07003939
3940void SurfaceFlinger::renderScreenImplLocked(
3941 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003942 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003943 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003944 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003945{
3946 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003947 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003948
3949 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003950 const int32_t hw_w = hw->getWidth();
3951 const int32_t hw_h = hw->getHeight();
3952 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003953 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003954
Dan Stozac1879002014-05-22 15:59:05 -07003955 // if a default or invalid sourceCrop is passed in, set reasonable values
3956 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3957 !sourceCrop.isValid()) {
3958 sourceCrop.setLeftTop(Point(0, 0));
3959 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3960 }
3961
3962 // ensure that sourceCrop is inside screen
3963 if (sourceCrop.left < 0) {
3964 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3965 }
Dan Stozabe31f442014-06-11 11:20:54 -07003966 if (sourceCrop.right > hw_w) {
3967 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003968 }
3969 if (sourceCrop.top < 0) {
3970 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3971 }
Dan Stozabe31f442014-06-11 11:20:54 -07003972 if (sourceCrop.bottom > hw_h) {
3973 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003974 }
3975
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003977 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003978
3979 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003980 engine.setViewportAndProjection(
3981 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003982 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003983
3984 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003985 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003986
Robert Carr1f0a16a2016-10-24 16:27:39 -07003987 // We loop through the first level of layers without traversing,
3988 // as we need to interpret min/max layer Z in the top level Z space.
3989 for (const auto& layer : mDrawingState.layersSortedByZ) {
3990 if (layer->getLayerStack() != hw->getLayerStack()) {
3991 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003992 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003993 const Layer::State& state(layer->getDrawingState());
3994 if (state.z < minLayerZ || state.z > maxLayerZ) {
3995 continue;
3996 }
3997 layer->traverseInZOrder([&](Layer* layer) {
3998 if (!layer->isVisible()) {
3999 return;
4000 }
4001 if (filtering) layer->setFiltering(true);
4002 layer->draw(hw, useIdentityTransform);
4003 if (filtering) layer->setFiltering(false);
4004 });
4005 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004006
Mathias Agopian931bda12013-08-28 18:11:46 -07004007 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004008}
4009
4010
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004011status_t SurfaceFlinger::captureScreenImplLocked(
4012 const sp<const DisplayDevice>& hw,
4013 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004014 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004015 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004016 bool useIdentityTransform, Transform::orientation_flags rotation,
4017 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004018{
4019 ATRACE_CALL();
4020
Mathias Agopian180f10d2013-04-10 22:55:41 -07004021 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004022 uint32_t hw_w = hw->getWidth();
4023 uint32_t hw_h = hw->getHeight();
4024
4025 if (rotation & Transform::ROT_90) {
4026 std::swap(hw_w, hw_h);
4027 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004028
Mathias Agopian180f10d2013-04-10 22:55:41 -07004029 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4030 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4031 reqWidth, reqHeight, hw_w, hw_h);
4032 return BAD_VALUE;
4033 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004034
Mathias Agopian180f10d2013-04-10 22:55:41 -07004035 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4036 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4037
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004038 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004039 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004040 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004041 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4042 (state.z < minLayerZ || state.z > maxLayerZ)) {
4043 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004044 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004045 layer->traverseInZOrder([&](Layer *layer) {
4046 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4047 layer->isSecure());
4048 });
4049 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004050
4051 if (!isLocalScreenshot && secureLayerIsVisible) {
4052 ALOGW("FB is protected: PERMISSION_DENIED");
4053 return PERMISSION_DENIED;
4054 }
4055
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004056 // create a surface (because we're a producer, and we need to
4057 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004058 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004059
4060 // Put the screenshot Surface into async mode so that
4061 // Layer::headFenceHasSignaled will always return true and we'll latch the
4062 // first buffer regardless of whether or not its acquire fence has
4063 // signaled. This is needed to avoid a race condition in the rotation
4064 // animation. See b/30209608
4065 sur->setAsyncMode(true);
4066
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004067 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004068
Michael Lentine5a16a622015-05-21 13:48:24 -07004069 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4070 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004071 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4072 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004073
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 int err = 0;
4075 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004076 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004077 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4078 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004079
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004080 if (err == NO_ERROR) {
4081 ANativeWindowBuffer* buffer;
4082 /* TODO: Once we have the sync framework everywhere this can use
4083 * server-side waits on the fence that dequeueBuffer returns.
4084 */
4085 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4086 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004087 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004088 // create an EGLImage from the buffer so we can later
4089 // turn it into a texture
4090 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4091 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4092 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004093 // this binds the given EGLImage as a framebuffer for the
4094 // duration of this scope.
4095 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4096 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004097 // this will in fact render into our dequeued buffer
4098 // via an FBO, which means we didn't have to create
4099 // an EGLSurface and therefore we're not
4100 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004101 renderScreenImplLocked(
4102 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4103 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004104
Riley Andrews86639902014-08-15 12:27:24 -07004105 // Attempt to create a sync khr object that can produce a sync point. If that
4106 // isn't available, create a non-dupable sync object in the fallback path and
4107 // wait on it directly.
4108 EGLSyncKHR sync;
4109 if (!DEBUG_SCREENSHOTS) {
4110 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004111 // native fence fd will not be populated until flush() is done.
4112 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004113 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004114 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004115 }
Riley Andrews86639902014-08-15 12:27:24 -07004116 if (sync != EGL_NO_SYNC_KHR) {
4117 // get the sync fd
4118 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4119 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4120 ALOGW("captureScreen: failed to dup sync khr object");
4121 syncFd = -1;
4122 }
4123 eglDestroySyncKHR(mEGLDisplay, sync);
4124 } else {
4125 // fallback path
4126 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4127 if (sync != EGL_NO_SYNC_KHR) {
4128 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4129 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4130 EGLint eglErr = eglGetError();
4131 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4132 ALOGW("captureScreen: fence wait timed out");
4133 } else {
4134 ALOGW_IF(eglErr != EGL_SUCCESS,
4135 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4136 }
4137 eglDestroySyncKHR(mEGLDisplay, sync);
4138 } else {
4139 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4140 }
4141 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004142 if (DEBUG_SCREENSHOTS) {
4143 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4144 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4145 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4146 hw, minLayerZ, maxLayerZ);
4147 delete [] pixels;
4148 }
4149
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004150 } else {
4151 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4152 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004153 window->cancelBuffer(window, buffer, syncFd);
4154 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004155 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004156 // destroy our image
4157 eglDestroyImageKHR(mEGLDisplay, image);
4158 } else {
4159 result = BAD_VALUE;
4160 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004161 if (buffer) {
4162 // queueBuffer takes ownership of syncFd
4163 result = window->queueBuffer(window, buffer, syncFd);
4164 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004165 }
4166 } else {
4167 result = BAD_VALUE;
4168 }
4169 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4170 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004171
Mathias Agopian74c40c02010-09-29 13:02:36 -07004172 return result;
4173}
4174
Mathias Agopiand5556842013-09-19 17:08:37 -07004175void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004176 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004177 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004178 for (size_t y=0 ; y<h ; y++) {
4179 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4180 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004181 if (p[x] != 0xFF000000) return;
4182 }
4183 }
4184 ALOGE("*** we just took a black screenshot ***\n"
4185 "requested minz=%d, maxz=%d, layerStack=%d",
4186 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004187
Robert Carr2047fae2016-11-28 14:09:09 -08004188 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004189 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004190 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4192 state.z <= maxLayerZ) {
4193 layer->traverseInZOrder([&](Layer* layer) {
4194 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4195 layer->isVisible() ? '+' : '-',
4196 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004197 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004198 i++;
4199 });
4200 }
4201 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004202 }
4203}
4204
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004205// ---------------------------------------------------------------------------
4206
Robert Carr2047fae2016-11-28 14:09:09 -08004207void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4208 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004209}
4210
Robert Carr2047fae2016-11-28 14:09:09 -08004211void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4212 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004213}
4214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004215}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004216
4217
4218#if defined(__gl_h_)
4219#error "don't include gl/gl.h in this file"
4220#endif
4221
4222#if defined(__gl2_h_)
4223#error "don't include gl2/gl2.h in this file"
4224#endif