blob: 4798ecdedd22e78507f12afe059f434dab4e423e [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 Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
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>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Mathias Agopiana4912602012-07-12 14:25:33 -070076#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070077#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070078#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopianff2ed702013-09-01 21:36:12 -070080#include "Effects/Daltonizer.h"
81
Mathias Agopian875d8e12013-06-07 15:35:48 -070082#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#define DISPLAY_COUNT 1
86
Mathias Agopianfee2b462013-07-03 12:34:01 -070087/*
88 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
89 * black pixels.
90 */
91#define DEBUG_SCREENSHOTS false
92
Mathias Agopianca088332013-03-28 17:44:13 -070093EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070097// This is the phase offset in nanoseconds of the software vsync event
98// relative to the vsync event reported by HWComposer. The software vsync
99// event is when SurfaceFlinger and Choreographer-based applications run each
100// frame.
101//
102// This phase offset allows adjustment of the minimum latency from application
103// wake-up (by Choregographer) time to the time at which the resulting window
104// image is displayed. This value may be either positive (after the HW vsync)
105// or negative (before the HW vsync). Setting it to 0 will result in a
106// minimum latency of two vsync periods because the app and SurfaceFlinger
107// will run just after the HW vsync. Setting it to a positive number will
108// result in the minimum latency being:
109//
110// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
111//
112// Note that reducing this latency makes it more likely for the applications
113// to not have their window content image ready in time. When this happens
114// the latency will end up being an additional vsync period, and animations
115// will hiccup. Therefore, this latency should be tuned somewhat
116// conservatively (or at least with awareness of the trade-off being made).
117static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
118
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700119// This is the phase offset at which SurfaceFlinger's composition runs.
120static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700132 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700134 mTransactionPending(false),
135 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700136 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700137 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700138 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700139 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800143 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800144 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700146 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700147 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700148 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700149 mDebugInSwapBuffers(0),
150 mLastSwapBufferTime(0),
151 mDebugInTransaction(0),
152 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700153 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700154 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700155 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000156 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700157 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700158 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800159 mHasColorMatrix(false),
160 mHasPoweredOff(false),
161 mFrameBuckets(),
162 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLastSwapTime(0),
164 mNumLayers(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165{
Steve Blocka19954a2012-01-04 20:05:49 +0000166 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167
168 // debugging stuff...
169 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700170
Mathias Agopianb4b17302013-03-20 18:36:41 -0700171 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700172 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 property_get("debug.sf.showupdates", value, "0");
175 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700176
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700177 property_get("debug.sf.ddms", value, "0");
178 mDebugDDMS = atoi(value);
179 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700180 if (!startDdmConnection()) {
181 // start failed, and DDMS debugging not enabled
182 mDebugDDMS = 0;
183 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700184 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700185 ALOGI_IF(mDebugRegion, "showupdates enabled");
186 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700187
188 property_get("debug.sf.disable_backpressure", value, "0");
189 mPropagateBackpressure = !atoi(value);
190 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700191
192 property_get("debug.sf.disable_hwc_vds", value, "0");
193 mUseHwcVirtualDisplays = !atoi(value);
194 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800195
196 property_get("ro.sf.disable_triple_buffer", value, "0");
197 mLayerTripleBufferingDisabled = !atoi(value);
198 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199}
200
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800201void SurfaceFlinger::onFirstRef()
202{
203 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800204}
205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206SurfaceFlinger::~SurfaceFlinger()
207{
Mathias Agopiana4912602012-07-12 14:25:33 -0700208 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
209 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
210 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211}
212
Dan Stozac7014012014-02-14 15:03:43 -0800213void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800214{
215 // the window manager died on us. prepare its eulogy.
216
Andy McFadden13a082e2012-08-24 10:16:42 -0700217 // restore initial conditions (default device unblank, etc)
218 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219
220 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700221 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800222}
223
Mathias Agopian7e27f052010-05-28 14:22:23 -0700224sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225{
Mathias Agopian96f08192010-06-02 23:28:45 -0700226 sp<ISurfaceComposerClient> bclient;
227 sp<Client> client(new Client(this));
228 status_t err = client->initCheck();
229 if (err == NO_ERROR) {
230 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 return bclient;
233}
234
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700235sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
236 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700237{
238 class DisplayToken : public BBinder {
239 sp<SurfaceFlinger> flinger;
240 virtual ~DisplayToken() {
241 // no more references, this display must be terminated
242 Mutex::Autolock _l(flinger->mStateLock);
243 flinger->mCurrentState.displays.removeItem(this);
244 flinger->setTransactionFlags(eDisplayTransactionNeeded);
245 }
246 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700247 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700248 : flinger(flinger) {
249 }
250 };
251
252 sp<BBinder> token = new DisplayToken(this);
253
254 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700255 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700256 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700257 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700258 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700259 return token;
260}
261
Jesse Hall6c913be2013-08-08 12:15:49 -0700262void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
263 Mutex::Autolock _l(mStateLock);
264
265 ssize_t idx = mCurrentState.displays.indexOfKey(display);
266 if (idx < 0) {
267 ALOGW("destroyDisplay: invalid display token");
268 return;
269 }
270
271 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
272 if (!info.isVirtualDisplay()) {
273 ALOGE("destroyDisplay called for non-virtual display");
274 return;
275 }
Irvelffc9efc2016-07-27 15:16:37 -0700276 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700277 mCurrentState.displays.removeItemsAt(idx);
278 setTransactionFlags(eDisplayTransactionNeeded);
279}
280
Jesse Hall692c7232012-11-08 15:41:56 -0800281void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800282 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800283 ALOGW_IF(mBuiltinDisplays[type],
284 "Overwriting display token for display type %d", type);
285 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800286 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700287 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800288 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700289 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800290}
291
Mathias Agopiane57f2922012-08-09 16:29:12 -0700292sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700293 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700294 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
295 return NULL;
296 }
Jesse Hall692c7232012-11-08 15:41:56 -0800297 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700298}
299
Jamie Gennis9a78c902011-01-12 18:30:40 -0800300sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
301{
302 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
303 return gba;
304}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306void SurfaceFlinger::bootFinished()
307{
308 const nsecs_t now = systemTime();
309 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000310 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700311 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700312
313 // wait patiently for the window manager death
314 const String16 name("window");
315 sp<IBinder> window(defaultServiceManager()->getService(name));
316 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700317 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700318 }
319
320 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700321 // formerly we would just kill the process, but we now ask it to exit so it
322 // can choose where to stop the animation.
323 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700324
325 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
326 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
327 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328}
329
Mathias Agopian3f844832013-08-07 21:24:32 -0700330void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700331 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700332 RenderEngine& engine;
333 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700334 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700335 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
336 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337 }
338 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700339 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700340 return true;
341 }
342 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700343 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700344}
345
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700346class DispSyncSource : public VSyncSource, private DispSync::Callback {
347public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700348 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000349 const char* name) :
350 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700351 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700352 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000353 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
354 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700355 mDispSync(dispSync),
356 mCallbackMutex(),
357 mCallback(),
358 mVsyncMutex(),
359 mPhaseOffset(phaseOffset),
360 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700361
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700362 virtual ~DispSyncSource() {}
363
364 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700365 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700366 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000367 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 static_cast<DispSync::Callback*>(this));
369 if (err != NO_ERROR) {
370 ALOGE("error registering vsync callback: %s (%d)",
371 strerror(-err), err);
372 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700373 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 } else {
375 status_t err = mDispSync->removeEventListener(
376 static_cast<DispSync::Callback*>(this));
377 if (err != NO_ERROR) {
378 ALOGE("error unregistering vsync callback: %s (%d)",
379 strerror(-err), err);
380 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700381 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700382 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700383 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700384 }
385
386 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700387 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700388 mCallback = callback;
389 }
390
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700391 virtual void setPhaseOffset(nsecs_t phaseOffset) {
392 Mutex::Autolock lock(mVsyncMutex);
393
394 // Normalize phaseOffset to [0, period)
395 auto period = mDispSync->getPeriod();
396 phaseOffset %= period;
397 if (phaseOffset < 0) {
398 // If we're here, then phaseOffset is in (-period, 0). After this
399 // operation, it will be in (0, period)
400 phaseOffset += period;
401 }
402 mPhaseOffset = phaseOffset;
403
404 // If we're not enabled, we don't need to mess with the listeners
405 if (!mEnabled) {
406 return;
407 }
408
409 // Remove the listener with the old offset
410 status_t err = mDispSync->removeEventListener(
411 static_cast<DispSync::Callback*>(this));
412 if (err != NO_ERROR) {
413 ALOGE("error unregistering vsync callback: %s (%d)",
414 strerror(-err), err);
415 }
416
417 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000418 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 static_cast<DispSync::Callback*>(this));
420 if (err != NO_ERROR) {
421 ALOGE("error registering vsync callback: %s (%d)",
422 strerror(-err), err);
423 }
424 }
425
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426private:
427 virtual void onDispSyncEvent(nsecs_t when) {
428 sp<VSyncSource::Callback> callback;
429 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 callback = mCallback;
432
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 if (mTraceVsync) {
434 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700436 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
438
439 if (callback != NULL) {
440 callback->onVSyncEvent(when);
441 }
442 }
443
Tim Murray4a4e4a22016-04-19 16:29:23 +0000444 const char* const mName;
445
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 int mValue;
447
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700449 const String8 mVsyncOnLabel;
450 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700451
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453
454 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700456
457 Mutex mVsyncMutex; // Protects the following
458 nsecs_t mPhaseOffset;
459 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460};
461
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700462class InjectVSyncSource : public VSyncSource {
463public:
464 InjectVSyncSource() {}
465
466 virtual ~InjectVSyncSource() {}
467
468 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
469 std::lock_guard<std::mutex> lock(mCallbackMutex);
470 mCallback = callback;
471 }
472
473 virtual void onInjectSyncEvent(nsecs_t when) {
474 std::lock_guard<std::mutex> lock(mCallbackMutex);
475 mCallback->onVSyncEvent(when);
476 }
477
478 virtual void setVSyncEnabled(bool) {}
479 virtual void setPhaseOffset(nsecs_t) {}
480
481private:
482 std::mutex mCallbackMutex; // Protects the following
483 sp<VSyncSource::Callback> mCallback;
484};
485
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700487 ALOGI( "SurfaceFlinger's main thread ready to run. "
488 "Initializing graphics H/W...");
489
Dan Stoza9e56aa02015-11-02 13:00:03 -0800490 { // Autolock scope
491 Mutex::Autolock _l(mStateLock);
492
493 // initialize EGL for the default display
494 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
495 eglInitialize(mEGLDisplay, NULL, NULL);
496
497 // start the EventThread
498 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
499 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700500 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800501 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
502 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700503 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800504 mEventQueue.setEventThread(mSFEventThread);
505
Tim Murrayacff43d2016-07-29 13:57:24 -0700506 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700507 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700508 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700509 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
510 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
511 }
512
Dan Stoza9e56aa02015-11-02 13:00:03 -0800513 // Get a RenderEngine for the given display / config (can't fail)
514 mRenderEngine = RenderEngine::create(mEGLDisplay,
515 HAL_PIXEL_FORMAT_RGBA_8888);
516 }
517
518 // Drop the state lock while we initialize the hardware composer. We drop
519 // the lock because on creation, it will call back into SurfaceFlinger to
520 // initialize the primary display.
521 mHwc = new HWComposer(this);
522 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
523
Jesse Hall692c7232012-11-08 15:41:56 -0800524 Mutex::Autolock _l(mStateLock);
525
Mathias Agopian875d8e12013-06-07 15:35:48 -0700526 // retrieve the EGL context that was selected/created
527 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700528
Mathias Agopianda27af92012-09-13 18:17:13 -0700529 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
530 "couldn't create EGLContext");
531
Dan Stoza9e56aa02015-11-02 13:00:03 -0800532 // make the GLContext current so that we can create textures when creating
533 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700534 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
535
Jamie Gennisd1700752013-10-14 12:22:52 -0700536 mEventControlThread = new EventControlThread(this);
537 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
538
Mathias Agopian92a979a2012-08-02 18:32:23 -0700539 // initialize our drawing state
540 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700541
Andy McFadden13a082e2012-08-24 10:16:42 -0700542 // set initial conditions (e.g. unblank default device)
543 initializeDisplays();
544
Dan Stoza4e637772016-07-28 13:31:51 -0700545 mRenderEngine->primeCache();
546
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700547 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700548 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700551}
552
Mathias Agopiana67e4182012-06-19 17:26:12 -0700553void SurfaceFlinger::startBootAnim() {
554 // start boot animation
555 property_set("service.bootanim.exit", "0");
556 property_set("ctl.start", "bootanim");
557}
558
Mathias Agopian875d8e12013-06-07 15:35:48 -0700559size_t SurfaceFlinger::getMaxTextureSize() const {
560 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700561}
562
Mathias Agopian875d8e12013-06-07 15:35:48 -0700563size_t SurfaceFlinger::getMaxViewportDims() const {
564 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700565}
566
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800568
Jamie Gennis582270d2011-08-17 18:19:00 -0700569bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800570 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800571 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800572 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700573 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800574}
575
Brian Anderson069b3652016-07-22 10:32:47 -0700576status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700577 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700578 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700579 FrameEvent::REQUESTED_PRESENT,
580 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700581 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700582 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700583 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700584 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700585 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700586 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700587 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700588 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700589 };
590 return NO_ERROR;
591}
592
Dan Stoza7f7da322014-05-02 15:26:25 -0700593status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
594 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700595 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700596 return BAD_VALUE;
597 }
598
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500599 if (!display.get())
600 return NAME_NOT_FOUND;
601
Jesse Hall692c7232012-11-08 15:41:56 -0800602 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700603 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800604 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700605 type = i;
606 break;
607 }
608 }
609
610 if (type < 0) {
611 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700612 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700613
Mathias Agopian8b736f12012-08-13 17:54:26 -0700614 // TODO: Not sure if display density should handled by SF any longer
615 class Density {
616 static int getDensityFromProperty(char const* propName) {
617 char property[PROPERTY_VALUE_MAX];
618 int density = 0;
619 if (property_get(propName, property, NULL) > 0) {
620 density = atoi(property);
621 }
622 return density;
623 }
624 public:
625 static int getEmuDensity() {
626 return getDensityFromProperty("qemu.sf.lcd_density"); }
627 static int getBuildDensity() {
628 return getDensityFromProperty("ro.sf.lcd_density"); }
629 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700630
Dan Stoza7f7da322014-05-02 15:26:25 -0700631 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700632
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700634 DisplayInfo info = DisplayInfo();
635
Dan Stoza9e56aa02015-11-02 13:00:03 -0800636 float xdpi = hwConfig->getDpiX();
637 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700638
639 if (type == DisplayDevice::DISPLAY_PRIMARY) {
640 // The density of the device is provided by a build property
641 float density = Density::getBuildDensity() / 160.0f;
642 if (density == 0) {
643 // the build doesn't provide a density -- this is wrong!
644 // use xdpi instead
645 ALOGE("ro.sf.lcd_density must be defined as a build property");
646 density = xdpi / 160.0f;
647 }
648 if (Density::getEmuDensity()) {
649 // if "qemu.sf.lcd_density" is specified, it overrides everything
650 xdpi = ydpi = density = Density::getEmuDensity();
651 density /= 160.0f;
652 }
653 info.density = density;
654
655 // TODO: this needs to go away (currently needed only by webkit)
656 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
657 info.orientation = hw->getOrientation();
658 } else {
659 // TODO: where should this value come from?
660 static const int TV_DENSITY = 213;
661 info.density = TV_DENSITY / 160.0f;
662 info.orientation = 0;
663 }
664
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665 info.w = hwConfig->getWidth();
666 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700667 info.xdpi = xdpi;
668 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700670 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800671
Andy McFadden91b2ca82014-06-13 14:04:23 -0700672 // This is how far in advance a buffer must be queued for
673 // presentation at a given time. If you want a buffer to appear
674 // on the screen at time N, you must submit the buffer before
675 // (N - presentationDeadline).
676 //
677 // Normally it's one full refresh period (to give SF a chance to
678 // latch the buffer), but this can be reduced by configuring a
679 // DispSync offset. Any additional delays introduced by the hardware
680 // composer or panel must be accounted for here.
681 //
682 // We add an additional 1ms to allow for processing time and
683 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800684 info.presentationDeadline = hwConfig->getVsyncPeriod() -
685 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700686
687 // All non-virtual displays are currently considered secure.
688 info.secure = true;
689
Michael Wright28f24d02016-07-12 13:30:53 -0700690 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700691 }
692
Dan Stoza7f7da322014-05-02 15:26:25 -0700693 return NO_ERROR;
694}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700695
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800696status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700697 DisplayStatInfo* stats) {
698 if (stats == NULL) {
699 return BAD_VALUE;
700 }
701
702 // FIXME for now we always return stats for the primary display
703 memset(stats, 0, sizeof(*stats));
704 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
705 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
706 return NO_ERROR;
707}
708
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700709int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800710 if (display == NULL) {
711 ALOGE("%s : display is NULL", __func__);
712 return BAD_VALUE;
713 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700714 sp<DisplayDevice> device(getDisplayDevice(display));
715 if (device != NULL) {
716 return device->getActiveConfig();
717 }
718 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700719}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700720
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700721void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
722 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
723 this);
724 int32_t type = hw->getDisplayType();
725 int currentMode = hw->getActiveConfig();
726
727 if (mode == currentMode) {
728 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
729 return;
730 }
731
732 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
733 ALOGW("Trying to set config for virtual display");
734 return;
735 }
736
737 hw->setActiveConfig(mode);
738 getHwComposer().setActiveConfig(type, mode);
739}
740
741status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
742 class MessageSetActiveConfig: public MessageBase {
743 SurfaceFlinger& mFlinger;
744 sp<IBinder> mDisplay;
745 int mMode;
746 public:
747 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
748 int mode) :
749 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
750 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700751 Vector<DisplayInfo> configs;
752 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700753 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700754 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700755 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700756 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700757 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700758 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
759 if (hw == NULL) {
760 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700761 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700762 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
763 ALOGW("Attempt to set active config = %d for virtual display",
764 mMode);
765 } else {
766 mFlinger.setActiveConfigInternal(hw, mMode);
767 }
768 return true;
769 }
770 };
771 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
772 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700773 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700774}
Michael Wright28f24d02016-07-12 13:30:53 -0700775status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
776 Vector<android_color_mode_t>* outColorModes) {
777 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
778 return BAD_VALUE;
779 }
780
781 if (!display.get()) {
782 return NAME_NOT_FOUND;
783 }
784
785 int32_t type = NAME_NOT_FOUND;
786 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
787 if (display == mBuiltinDisplays[i]) {
788 type = i;
789 break;
790 }
791 }
792
793 if (type < 0) {
794 return type;
795 }
796
797 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
798 outColorModes->clear();
799 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
800
801 return NO_ERROR;
802}
803
804android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
805 sp<DisplayDevice> device(getDisplayDevice(display));
806 if (device != nullptr) {
807 return device->getActiveColorMode();
808 }
809 return static_cast<android_color_mode_t>(BAD_VALUE);
810}
811
812void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
813 android_color_mode_t mode) {
814 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
815 this);
816 int32_t type = hw->getDisplayType();
817 android_color_mode_t currentMode = hw->getActiveColorMode();
818
819 if (mode == currentMode) {
820 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
821 return;
822 }
823
824 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
825 ALOGW("Trying to set config for virtual display");
826 return;
827 }
828
829 hw->setActiveColorMode(mode);
830 getHwComposer().setActiveColorMode(type, mode);
831}
832
833
834status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
835 android_color_mode_t colorMode) {
836 class MessageSetActiveColorMode: public MessageBase {
837 SurfaceFlinger& mFlinger;
838 sp<IBinder> mDisplay;
839 android_color_mode_t mMode;
840 public:
841 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
842 android_color_mode_t mode) :
843 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
844 virtual bool handler() {
845 Vector<android_color_mode_t> modes;
846 mFlinger.getDisplayColorModes(mDisplay, &modes);
847 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
848 if (mMode < 0 || !exists) {
849 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
850 mDisplay.get());
851 return true;
852 }
853 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
854 if (hw == nullptr) {
855 ALOGE("Attempt to set active color mode = %d for null display %p",
856 mMode, mDisplay.get());
857 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
858 ALOGW("Attempt to set active color mode= %d for virtual display",
859 mMode);
860 } else {
861 mFlinger.setActiveColorModeInternal(hw, mMode);
862 }
863 return true;
864 }
865 };
866 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
867 postMessageSync(msg);
868 return NO_ERROR;
869}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700870
Svetoslavd85084b2014-03-20 10:28:31 -0700871status_t SurfaceFlinger::clearAnimationFrameStats() {
872 Mutex::Autolock _l(mStateLock);
873 mAnimFrameTracker.clearStats();
874 return NO_ERROR;
875}
876
877status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
878 Mutex::Autolock _l(mStateLock);
879 mAnimFrameTracker.getStats(outStats);
880 return NO_ERROR;
881}
882
Dan Stozac4f471e2016-03-24 09:31:08 -0700883status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
884 HdrCapabilities* outCapabilities) const {
885 Mutex::Autolock _l(mStateLock);
886
887 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
888 if (displayDevice == nullptr) {
889 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
890 return BAD_VALUE;
891 }
892
893 std::unique_ptr<HdrCapabilities> capabilities =
894 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
895 if (capabilities) {
896 std::swap(*outCapabilities, *capabilities);
897 } else {
898 return BAD_VALUE;
899 }
900
901 return NO_ERROR;
902}
903
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700904status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
905 if (enable == mInjectVSyncs) {
906 return NO_ERROR;
907 }
908
909 if (enable) {
910 mInjectVSyncs = enable;
911 ALOGV("VSync Injections enabled");
912 if (mVSyncInjector.get() == nullptr) {
913 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700914 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700915 }
916 mEventQueue.setEventThread(mInjectorEventThread);
917 } else {
918 mInjectVSyncs = enable;
919 ALOGV("VSync Injections disabled");
920 mEventQueue.setEventThread(mSFEventThread);
921 mVSyncInjector.clear();
922 }
923 return NO_ERROR;
924}
925
926status_t SurfaceFlinger::injectVSync(nsecs_t when) {
927 if (!mInjectVSyncs) {
928 ALOGE("VSync Injections not enabled");
929 return BAD_VALUE;
930 }
931 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
932 ALOGV("Injecting VSync inside SurfaceFlinger");
933 mVSyncInjector->onInjectSyncEvent(when);
934 }
935 return NO_ERROR;
936}
937
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800938// ----------------------------------------------------------------------------
939
940sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800941 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700942}
943
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800944// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800945
946void SurfaceFlinger::waitForEvent() {
947 mEventQueue.waitMessage();
948}
949
950void SurfaceFlinger::signalTransaction() {
951 mEventQueue.invalidate();
952}
953
954void SurfaceFlinger::signalLayerUpdate() {
955 mEventQueue.invalidate();
956}
957
958void SurfaceFlinger::signalRefresh() {
959 mEventQueue.refresh();
960}
961
962status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800963 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800964 return mEventQueue.postMessage(msg, reltime);
965}
966
967status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800968 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800969 status_t res = mEventQueue.postMessage(msg, reltime);
970 if (res == NO_ERROR) {
971 msg->wait();
972 }
973 return res;
974}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700976void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700977 do {
978 waitForEvent();
979 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800980}
981
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700982void SurfaceFlinger::enableHardwareVsync() {
983 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700984 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700985 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700986 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
987 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700988 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700989 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700990}
991
Jesse Hall948fe0c2013-10-14 12:56:09 -0700992void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700993 Mutex::Autolock _l(mHWVsyncLock);
994
Jesse Hall948fe0c2013-10-14 12:56:09 -0700995 if (makeAvailable) {
996 mHWVsyncAvailable = true;
997 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700998 // Hardware vsync is not currently available, so abort the resync
999 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001000 return;
1001 }
1002
Dan Stoza9e56aa02015-11-02 13:00:03 -08001003 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1004 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001005
1006 mPrimaryDispSync.reset();
1007 mPrimaryDispSync.setPeriod(period);
1008
1009 if (!mPrimaryHWVsyncEnabled) {
1010 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001011 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1012 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001013 mPrimaryHWVsyncEnabled = true;
1014 }
1015}
1016
Jesse Hall948fe0c2013-10-14 12:56:09 -07001017void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001018 Mutex::Autolock _l(mHWVsyncLock);
1019 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001020 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1021 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001022 mPrimaryDispSync.endResync();
1023 mPrimaryHWVsyncEnabled = false;
1024 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001025 if (makeUnavailable) {
1026 mHWVsyncAvailable = false;
1027 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001028}
1029
Tim Murray4a4e4a22016-04-19 16:29:23 +00001030void SurfaceFlinger::resyncWithRateLimit() {
1031 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1032 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001033 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001034 }
1035}
1036
Dan Stoza9e56aa02015-11-02 13:00:03 -08001037void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001038 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001039
Jamie Gennisd1700752013-10-14 12:22:52 -07001040 { // Scope for the lock
1041 Mutex::Autolock _l(mHWVsyncLock);
1042 if (type == 0 && mPrimaryHWVsyncEnabled) {
1043 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001044 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001045 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001046
1047 if (needsHwVsync) {
1048 enableHardwareVsync();
1049 } else {
1050 disableHardwareVsync(false);
1051 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001052}
1053
Dan Stoza9e56aa02015-11-02 13:00:03 -08001054void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1055 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1056 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1057 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001058
Dan Stoza9e56aa02015-11-02 13:00:03 -08001059 // All non-virtual displays are currently considered secure.
1060 bool isSecure = true;
1061
1062 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1063 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1064 wp<IBinder> token = mBuiltinDisplays[type];
1065
1066 sp<IGraphicBufferProducer> producer;
1067 sp<IGraphicBufferConsumer> consumer;
1068 BufferQueue::createBufferQueue(&producer, &consumer,
1069 new GraphicBufferAlloc());
1070
1071 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1072 DisplayDevice::DISPLAY_PRIMARY, consumer);
1073 sp<DisplayDevice> hw = new DisplayDevice(this,
1074 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1075 producer, mRenderEngine->getEGLConfig());
1076 mDisplays.add(token, hw);
1077 } else {
1078 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001079 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001080 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001081 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001082 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001083 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1084 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001085 }
1086 setTransactionFlags(eDisplayTransactionNeeded);
1087
Andy McFadden9e9689c2012-10-10 18:17:51 -07001088 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001089 }
Mathias Agopian86303202012-07-24 22:46:10 -07001090}
1091
Dan Stoza9e56aa02015-11-02 13:00:03 -08001092void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001094 getHwComposer().setVsyncEnabled(disp,
1095 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001096}
1097
Mathias Agopian4fec8732012-06-29 14:12:52 -07001098void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001099 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001100 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001101 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001102 bool frameMissed = !mHadClientComposition &&
1103 mPreviousPresentFence != Fence::NO_FENCE &&
1104 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1105 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001106 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001107 signalLayerUpdate();
1108 break;
1109 }
1110
Dan Stoza6b9454d2014-11-07 16:00:59 -08001111 bool refreshNeeded = handleMessageTransaction();
1112 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001113 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001114 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001115 // Signal a refresh if a transaction modified the window state,
1116 // a new buffer was latched, or if HWC has requested a full
1117 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001118 signalRefresh();
1119 }
1120 break;
1121 }
1122 case MessageQueue::REFRESH: {
1123 handleMessageRefresh();
1124 break;
1125 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001126 }
1127}
1128
Dan Stoza6b9454d2014-11-07 16:00:59 -08001129bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001130 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001131 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001132 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001133 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001134 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001135 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001136}
1137
Dan Stoza6b9454d2014-11-07 16:00:59 -08001138bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001139 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001140 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001141}
1142
1143void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001144 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001145
Pablo Ceballos40845df2016-01-25 17:41:15 -08001146 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001147
Brian Andersond6927fb2016-07-23 23:37:30 -07001148 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001149 rebuildLayerStacks();
1150 setUpHWComposer();
1151 doDebugFlashRegions();
1152 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001153 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001154
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001155 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001156
1157 mHadClientComposition = false;
1158 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1159 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1160 mHadClientComposition = mHadClientComposition ||
1161 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1162 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001163
Dan Stoza9e56aa02015-11-02 13:00:03 -08001164 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001165}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001166
Mathias Agopiancd60f992012-08-16 16:28:27 -07001167void SurfaceFlinger::doDebugFlashRegions()
1168{
1169 // is debugging enabled
1170 if (CC_LIKELY(!mDebugRegion))
1171 return;
1172
1173 const bool repaintEverything = mRepaintEverything;
1174 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1175 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001176 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001177 // transform the dirty region into this screen's coordinate space
1178 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1179 if (!dirtyRegion.isEmpty()) {
1180 // redraw the whole screen
1181 doComposeSurfaces(hw, Region(hw->bounds()));
1182
1183 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001184 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001185 RenderEngine& engine(getRenderEngine());
1186 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1187
Mathias Agopianda27af92012-09-13 18:17:13 -07001188 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001189 }
1190 }
1191 }
1192
1193 postFramebuffer();
1194
1195 if (mDebugRegion > 1) {
1196 usleep(mDebugRegion * 1000);
1197 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001198
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001200 auto& displayDevice = mDisplays[displayId];
1201 if (!displayDevice->isDisplayOn()) {
1202 continue;
1203 }
1204
1205 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001206 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1207 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001208 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001209}
1210
Brian Andersond6927fb2016-07-23 23:37:30 -07001211void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001212{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001213 ATRACE_CALL();
1214 ALOGV("preComposition");
1215
Mathias Agopiancd60f992012-08-16 16:28:27 -07001216 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001217 mDrawingState.traverseInZOrder([&](Layer* layer) {
1218 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001219 needExtraInvalidate = true;
1220 }
Robert Carr2047fae2016-11-28 14:09:09 -08001221 });
1222
Mathias Agopiancd60f992012-08-16 16:28:27 -07001223 if (needExtraInvalidate) {
1224 signalLayerUpdate();
1225 }
1226}
1227
Brian Andersond6927fb2016-07-23 23:37:30 -07001228void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001229{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001230 ATRACE_CALL();
1231 ALOGV("postComposition");
1232
Brian Anderson3546a3f2016-07-14 11:51:14 -07001233 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001234 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001235 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001236 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001237 }
1238
Brian Andersond6927fb2016-07-23 23:37:30 -07001239 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001240
1241 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1242 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1243 glCompositionDoneFenceTime =
1244 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1245 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1246 } else {
1247 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1248 }
1249 mGlCompositionDoneTimeline.updateSignalTimes();
1250
1251 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1252 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1253 mDisplayTimeline.push(displayFenceTime);
1254 mDisplayTimeline.updateSignalTimes();
1255
1256 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1257 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1258 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1259 presentFenceTime = &displayFenceTime;
1260 } else {
1261 retireFenceTime = &displayFenceTime;
1262 }
Robert Carr2047fae2016-11-28 14:09:09 -08001263 mDrawingState.traverseInZOrder([&](Layer* layer) {
1264 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1265 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001266 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001267 recordBufferingStats(layer->getName().string(),
1268 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001269 }
Robert Carr2047fae2016-11-28 14:09:09 -08001270 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001271
Brian Anderson3d4039d2016-09-23 16:31:30 -07001272 if (displayFence->isValid()) {
1273 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 enableHardwareVsync();
1275 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
1278 }
1279
Andy McFadden5167ec62014-05-22 13:08:43 -07001280 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001281 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 enableHardwareVsync();
1283 }
1284 }
1285
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001286 if (mAnimCompositionPending) {
1287 mAnimCompositionPending = false;
1288
Brian Anderson3d4039d2016-09-23 16:31:30 -07001289 if (displayFenceTime->isValid()) {
1290 mAnimFrameTracker.setActualPresentFence(
1291 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001292 } else {
1293 // The HWC doesn't support present fences, so use the refresh
1294 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001295 nsecs_t presentTime =
1296 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001297 mAnimFrameTracker.setActualPresentTime(presentTime);
1298 }
1299 mAnimFrameTracker.advanceFrame();
1300 }
Dan Stozab90cf072015-03-05 11:05:59 -08001301
1302 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1303 return;
1304 }
1305
1306 nsecs_t currentTime = systemTime();
1307 if (mHasPoweredOff) {
1308 mHasPoweredOff = false;
1309 } else {
1310 nsecs_t period = mPrimaryDispSync.getPeriod();
1311 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1312 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1313 if (numPeriods < NUM_BUCKETS - 1) {
1314 mFrameBuckets[numPeriods] += elapsedTime;
1315 } else {
1316 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1317 }
1318 mTotalTime += elapsedTime;
1319 }
1320 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001321}
1322
1323void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001324 ATRACE_CALL();
1325 ALOGV("rebuildLayerStacks");
1326
Mathias Agopiancd60f992012-08-16 16:28:27 -07001327 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001328 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001329 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001330 mVisibleRegionsDirty = false;
1331 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001332
Mathias Agopian92a979a2012-08-02 18:32:23 -07001333 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001334 Region opaqueRegion;
1335 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001336 Vector<sp<Layer>> layersSortedByZ;
1337 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1338 const Transform& tr(displayDevice->getTransform());
1339 const Rect bounds(displayDevice->getBounds());
1340 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001341 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 displayDevice->getLayerStack(), dirtyRegion,
1343 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001344
Robert Carr2047fae2016-11-28 14:09:09 -08001345 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001346 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001347 Region drawRegion(tr.transform(
1348 layer->visibleNonTransparentRegion));
1349 drawRegion.andSelf(bounds);
1350 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001351 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 } else {
1353 // Clear out the HWC layer if this layer was
1354 // previously visible, but no longer is
1355 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1356 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001357 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001358 }
Robert Carr2047fae2016-11-28 14:09:09 -08001359 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001360 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1362 displayDevice->undefinedRegion.set(bounds);
1363 displayDevice->undefinedRegion.subtractSelf(
1364 tr.transform(opaqueRegion));
1365 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001366 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001367 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001368}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001369
Mathias Agopiancd60f992012-08-16 16:28:27 -07001370void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 ATRACE_CALL();
1372 ALOGV("setUpHWComposer");
1373
Jesse Hall028dc8f2013-08-20 16:35:32 -07001374 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001375 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1376 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1377 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1378
1379 // If nothing has changed (!dirty), don't recompose.
1380 // If something changed, but we don't currently have any visible layers,
1381 // and didn't when we last did a composition, then skip it this time.
1382 // The second rule does two things:
1383 // - When all layers are removed from a display, we'll emit one black
1384 // frame, then nothing more until we get new layers.
1385 // - When a display is created with a private layer stack, we won't
1386 // emit any black frames until a layer is added to the layer stack.
1387 bool mustRecompose = dirty && !(empty && wasEmpty);
1388
1389 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1390 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1391 mustRecompose ? "doing" : "skipping",
1392 dirty ? "+" : "-",
1393 empty ? "+" : "-",
1394 wasEmpty ? "+" : "-");
1395
Dan Stoza71433162014-02-04 16:22:36 -08001396 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001397
1398 if (mustRecompose) {
1399 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1400 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001401 }
1402
Dan Stoza9e56aa02015-11-02 13:00:03 -08001403 // build the h/w work list
1404 if (CC_UNLIKELY(mGeometryInvalid)) {
1405 mGeometryInvalid = false;
1406 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1407 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1408 const auto hwcId = displayDevice->getHwcDisplayId();
1409 if (hwcId >= 0) {
1410 const Vector<sp<Layer>>& currentLayers(
1411 displayDevice->getVisibleLayersSortedByZ());
1412 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001413 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001414 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001415 if (!layer->hasHwcLayer(hwcId)) {
1416 auto hwcLayer = mHwc->createLayer(hwcId);
1417 if (hwcLayer) {
1418 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1419 } else {
1420 layer->forceClientComposition(hwcId);
1421 foundLayerWithoutHwc = true;
1422 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001423 }
1424 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001425
Robert Carrae060832016-11-28 10:51:00 -08001426 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001427 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001428 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001429 }
1430 }
1431 }
1432 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 }
Riley Andrews03414a12014-07-01 14:22:59 -07001434
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001435
1436 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1437
Dan Stoza9e56aa02015-11-02 13:00:03 -08001438 // Set the per-frame data
1439 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1440 auto& displayDevice = mDisplays[displayId];
1441 const auto hwcId = displayDevice->getHwcDisplayId();
1442 if (hwcId < 0) {
1443 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001444 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001445 if (colorMatrix != mPreviousColorMatrix) {
1446 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1447 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1448 "display %zd: %d", displayId, result);
1449 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1451 layer->setPerFrameData(displayDevice);
1452 }
1453 }
1454
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001455 mPreviousColorMatrix = colorMatrix;
1456
Dan Stoza9e56aa02015-11-02 13:00:03 -08001457 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001458 auto& displayDevice = mDisplays[displayId];
1459 if (!displayDevice->isDisplayOn()) {
1460 continue;
1461 }
1462
1463 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001464 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1465 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001466 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001468
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469void SurfaceFlinger::doComposition() {
1470 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001471 ALOGV("doComposition");
1472
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001473 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001474 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001475 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001476 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 // transform the dirty region into this screen's coordinate space
1478 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001479
1480 // repaint the framebuffer (if needed)
1481 doDisplayComposition(hw, dirtyRegion);
1482
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483 hw->dirtyRegion.clear();
1484 hw->flip(hw->swapRegion);
1485 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001486 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001487 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001488 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489}
1490
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001491void SurfaceFlinger::postFramebuffer()
1492{
Mathias Agopian841cde52012-03-01 15:44:37 -08001493 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001494 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001495
Mathias Agopiana44b0412011-10-16 18:46:35 -07001496 const nsecs_t now = systemTime();
1497 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1500 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001501 if (!displayDevice->isDisplayOn()) {
1502 continue;
1503 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001504 const auto hwcId = displayDevice->getHwcDisplayId();
1505 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001506 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001507 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001508 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001509 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1511 sp<Fence> releaseFence = Fence::NO_FENCE;
1512 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1513 releaseFence = displayDevice->getClientTargetAcquireFence();
1514 } else {
1515 auto hwcLayer = layer->getHwcLayer(hwcId);
1516 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001517 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001518 layer->onLayerDisplayed(releaseFence);
1519 }
1520 if (hwcId >= 0) {
1521 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001522 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001523 }
1524
Mathias Agopiana44b0412011-10-16 18:46:35 -07001525 mLastSwapBufferTime = systemTime() - now;
1526 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001527
1528 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1529 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1530 logFrameStats();
1531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001532}
1533
Mathias Agopian87baae12012-07-31 12:38:26 -07001534void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535{
Mathias Agopian841cde52012-03-01 15:44:37 -08001536 ATRACE_CALL();
1537
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001538 // here we keep a copy of the drawing state (that is the state that's
1539 // going to be overwritten by handleTransactionLocked()) outside of
1540 // mStateLock so that the side-effects of the State assignment
1541 // don't happen with mStateLock held (which can cause deadlocks).
1542 State drawingState(mDrawingState);
1543
Mathias Agopianca4d3602011-05-19 15:38:14 -07001544 Mutex::Autolock _l(mStateLock);
1545 const nsecs_t now = systemTime();
1546 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547
Mathias Agopianca4d3602011-05-19 15:38:14 -07001548 // Here we're guaranteed that some transaction flags are set
1549 // so we can call handleTransactionLocked() unconditionally.
1550 // We call getTransactionFlags(), which will also clear the flags,
1551 // with mStateLock held to guarantee that mCurrentState won't change
1552 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001553
Mathias Agopiane57f2922012-08-09 16:29:12 -07001554 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001555 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001556
Mathias Agopianca4d3602011-05-19 15:38:14 -07001557 mLastTransactionTime = systemTime() - now;
1558 mDebugInTransaction = 0;
1559 invalidateHwcGeometry();
1560 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001561}
1562
Mathias Agopian87baae12012-07-31 12:38:26 -07001563void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001564{
Dan Stoza7dde5992015-05-22 09:51:44 -07001565 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001566 mCurrentState.traverseInZOrder([](Layer* layer) {
1567 layer->notifyAvailableFrames();
1568 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001569
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001570 /*
1571 * Traversal of the children
1572 * (perform the transaction for each of them if needed)
1573 */
1574
Mathias Agopian3559b072012-08-15 13:46:03 -07001575 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001576 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001577 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001578 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001579
1580 const uint32_t flags = layer->doTransaction(0);
1581 if (flags & Layer::eVisibleRegion)
1582 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001583 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001584 }
1585
1586 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001587 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001588 */
1589
Mathias Agopiane57f2922012-08-09 16:29:12 -07001590 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001591 // here we take advantage of Vector's copy-on-write semantics to
1592 // improve performance by skipping the transaction entirely when
1593 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001594 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1595 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001596 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001597 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001598 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001599 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001600
1601 // find the displays that were removed
1602 // (ie: in drawing state but not in current state)
1603 // also handle displays that changed
1604 // (ie: displays that are in both lists)
1605 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001606 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1607 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001608 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001609 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001610 // Call makeCurrent() on the primary display so we can
1611 // be sure that nothing associated with this display
1612 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001613 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001614 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001615 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1616 if (hw != NULL)
1617 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001618 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001619 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001620 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001621 } else {
1622 ALOGW("trying to remove the main display");
1623 }
1624 } else {
1625 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001626 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001627 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001628 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1629 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001630 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001631 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001632 // recreating the DisplayDevice, so we just remove it
1633 // from the drawing state, so that it get re-added
1634 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001635 sp<DisplayDevice> hw(getDisplayDevice(display));
1636 if (hw != NULL)
1637 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001638 mDisplays.removeItem(display);
1639 mDrawingState.displays.removeItemsAt(i);
1640 dc--; i--;
1641 // at this point we must loop to the next item
1642 continue;
1643 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001644
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001645 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001646 if (disp != NULL) {
1647 if (state.layerStack != draw[i].layerStack) {
1648 disp->setLayerStack(state.layerStack);
1649 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001650 if ((state.orientation != draw[i].orientation)
1651 || (state.viewport != draw[i].viewport)
1652 || (state.frame != draw[i].frame))
1653 {
1654 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001655 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001656 }
Michael Lentine47e45402014-07-18 15:34:25 -07001657 if (state.width != draw[i].width || state.height != draw[i].height) {
1658 disp->setDisplaySize(state.width, state.height);
1659 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001660 }
1661 }
1662 }
1663
1664 // find displays that were added
1665 // (ie: in current state but not in drawing state)
1666 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001667 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001668 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001669
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001670 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001671 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001672 sp<IGraphicBufferProducer> bqProducer;
1673 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001674 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1675 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001676
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001678 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001679 // Virtual displays without a surface are dormant:
1680 // they have external state (layer stack, projection,
1681 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001682 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001683
Dan Stoza8cf150a2016-08-02 10:27:31 -07001684 if (mUseHwcVirtualDisplays) {
1685 int width = 0;
1686 int status = state.surface->query(
1687 NATIVE_WINDOW_WIDTH, &width);
1688 ALOGE_IF(status != NO_ERROR,
1689 "Unable to query width (%d)", status);
1690 int height = 0;
1691 status = state.surface->query(
1692 NATIVE_WINDOW_HEIGHT, &height);
1693 ALOGE_IF(status != NO_ERROR,
1694 "Unable to query height (%d)", status);
1695 int intFormat = 0;
1696 status = state.surface->query(
1697 NATIVE_WINDOW_FORMAT, &intFormat);
1698 ALOGE_IF(status != NO_ERROR,
1699 "Unable to query format (%d)", status);
1700 auto format = static_cast<android_pixel_format_t>(
1701 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001702
Dan Stoza8cf150a2016-08-02 10:27:31 -07001703 mHwc->allocateVirtualDisplay(width, height, &format,
1704 &hwcId);
1705 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706
Dan Stoza5cf424b2016-05-20 14:02:39 -07001707 // TODO: Plumb requested format back up to consumer
1708
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 sp<VirtualDisplaySurface> vds =
1710 new VirtualDisplaySurface(*mHwc,
1711 hwcId, state.surface, bqProducer,
1712 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001713
1714 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001715 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001716 }
1717 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001718 ALOGE_IF(state.surface!=NULL,
1719 "adding a supported display, but rendering "
1720 "surface is provided (%p), ignoring it",
1721 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1723 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1724 dispSurface = new FramebufferSurface(*mHwc,
1725 DisplayDevice::DISPLAY_EXTERNAL,
1726 bqConsumer);
1727 producer = bqProducer;
1728 } else {
1729 ALOGE("Attempted to add non-external non-virtual"
1730 " display");
1731 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001732 }
1733
1734 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001735 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001736 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 state.type, hwcId, state.isSecure, display,
1738 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001739 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001740 hw->setLayerStack(state.layerStack);
1741 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001742 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001743 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001744 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001746 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001747 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001748 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001749 }
1750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001753
Mathias Agopian84300952012-11-21 16:02:13 -08001754 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1755 // The transform hint might have changed for some layers
1756 // (either because a display has changed, or because a layer
1757 // as changed).
1758 //
1759 // Walk through all the layers in currentLayers,
1760 // and update their transform hint.
1761 //
1762 // If a layer is visible only on a single display, then that
1763 // display is used to calculate the hint, otherwise we use the
1764 // default display.
1765 //
1766 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1767 // the hint is set before we acquire a buffer from the surface texture.
1768 //
1769 // NOTE: layer transactions have taken place already, so we use their
1770 // drawing state. However, SurfaceFlinger's own transaction has not
1771 // happened yet, so we must use the current state layer list
1772 // (soon to become the drawing state list).
1773 //
1774 sp<const DisplayDevice> disp;
1775 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001776 bool first = true;
1777 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001778 // NOTE: we rely on the fact that layers are sorted by
1779 // layerStack first (so we don't have to traverse the list
1780 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001781 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001782 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001783 currentlayerStack = layerStack;
1784 // figure out if this layerstack is mirrored
1785 // (more than one display) if so, pick the default display,
1786 // if not, pick the only display it's on.
1787 disp.clear();
1788 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1789 sp<const DisplayDevice> hw(mDisplays[dpy]);
1790 if (hw->getLayerStack() == currentlayerStack) {
1791 if (disp == NULL) {
1792 disp = hw;
1793 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001794 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001795 break;
1796 }
1797 }
1798 }
1799 }
Chet Haase91d25932013-04-11 15:24:55 -07001800 if (disp == NULL) {
1801 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1802 // redraw after transform hint changes. See bug 8508397.
1803
1804 // could be null when this layer is using a layerStack
1805 // that is not visible on any display. Also can occur at
1806 // screen off/on times.
1807 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001808 }
Chet Haase91d25932013-04-11 15:24:55 -07001809 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001810
1811 first = false;
1812 });
Mathias Agopian84300952012-11-21 16:02:13 -08001813 }
1814
1815
Mathias Agopian3559b072012-08-15 13:46:03 -07001816 /*
1817 * Perform our own transaction if needed
1818 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001819
1820 if (mLayersAdded) {
1821 mLayersAdded = false;
1822 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001823 mVisibleRegionsDirty = true;
1824 }
1825
1826 // some layers might have been removed, so
1827 // we need to update the regions they're exposing.
1828 if (mLayersRemoved) {
1829 mLayersRemoved = false;
1830 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001831 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001833 // this layer is not visible anymore
1834 // TODO: we could traverse the tree from front to back and
1835 // compute the actual visible region
1836 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001837 Region visibleReg;
1838 visibleReg.set(layer->computeScreenBounds());
1839 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001840 }
Robert Carr2047fae2016-11-28 14:09:09 -08001841 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001842 }
1843
1844 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001845
1846 updateCursorAsync();
1847}
1848
1849void SurfaceFlinger::updateCursorAsync()
1850{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001851 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1852 auto& displayDevice = mDisplays[displayId];
1853 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001854 continue;
1855 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001856
1857 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1858 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001859 }
1860 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001861}
1862
1863void SurfaceFlinger::commitTransaction()
1864{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001865 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001866 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001867 for (const auto& l : mLayersPendingRemoval) {
1868 recordBufferingStats(l->getName().string(),
1869 l->getOccupancyHistory(true));
1870 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001871 }
1872 mLayersPendingRemoval.clear();
1873 }
1874
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001875 // If this transaction is part of a window animation then the next frame
1876 // we composite should be considered an animation as well.
1877 mAnimCompositionPending = mAnimTransactionPending;
1878
Mathias Agopian4fec8732012-06-29 14:12:52 -07001879 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001880 mDrawingState.traverseInZOrder([](Layer* layer) {
1881 layer->commitChildList();
1882 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001883 mTransactionPending = false;
1884 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001885 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886}
1887
Robert Carr2047fae2016-11-28 14:09:09 -08001888void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07001889 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001890{
Mathias Agopian841cde52012-03-01 15:44:37 -08001891 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001893
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001894 Region aboveOpaqueLayers;
1895 Region aboveCoveredLayers;
1896 Region dirty;
1897
Mathias Agopian87baae12012-07-31 12:38:26 -07001898 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899
Robert Carr2047fae2016-11-28 14:09:09 -08001900 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001901 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001902 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001903
Jesse Hall01e29052013-02-19 16:13:35 -08001904 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001906 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07001907
Mathias Agopianab028732010-03-16 16:41:46 -07001908 /*
1909 * opaqueRegion: area of a surface that is fully opaque.
1910 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001912
1913 /*
1914 * visibleRegion: area of a surface that is visible on screen
1915 * and not fully transparent. This is essentially the layer's
1916 * footprint minus the opaque regions above it.
1917 * Areas covered by a translucent surface are considered visible.
1918 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001919 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001920
1921 /*
1922 * coveredRegion: area of a surface that is covered by all
1923 * visible regions above it (which includes the translucent areas).
1924 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001926
Jesse Halla8026d22012-09-25 13:25:04 -07001927 /*
1928 * transparentRegion: area of a surface that is hinted to be completely
1929 * transparent. This is only used to tell when the layer has no visible
1930 * non-transparent regions and can be removed from the layer list. It
1931 * does not affect the visibleRegion of this layer or any layers
1932 * beneath it. The hint may not be correct if apps don't respect the
1933 * SurfaceView restrictions (which, sadly, some don't).
1934 */
1935 Region transparentRegion;
1936
Mathias Agopianab028732010-03-16 16:41:46 -07001937
1938 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001939 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001940 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001941 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001942 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001943 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07001944 if (!visibleRegion.isEmpty()) {
1945 // Remove the transparent area from the visible region
1946 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001947 if (tr.preserveRects()) {
1948 // transform the transparent region
1949 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001950 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001951 // transformation too complex, can't do the
1952 // transparent region optimization.
1953 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001954 }
Mathias Agopianab028732010-03-16 16:41:46 -07001955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001956
Mathias Agopianab028732010-03-16 16:41:46 -07001957 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001958 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001960 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1961 // the opaque region is the layer's footprint
1962 opaqueRegion = visibleRegion;
1963 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001964 }
1965 }
1966
Mathias Agopianab028732010-03-16 16:41:46 -07001967 // Clip the covered region to the visible region
1968 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1969
1970 // Update aboveCoveredLayers for next (lower) layer
1971 aboveCoveredLayers.orSelf(visibleRegion);
1972
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973 // subtract the opaque region covered by the layers above us
1974 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975
1976 // compute this layer's dirty region
1977 if (layer->contentDirty) {
1978 // we need to invalidate the whole region
1979 dirty = visibleRegion;
1980 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001981 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001982 layer->contentDirty = false;
1983 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001984 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001985 * the exposed region consists of two components:
1986 * 1) what's VISIBLE now and was COVERED before
1987 * 2) what's EXPOSED now less what was EXPOSED before
1988 *
1989 * note that (1) is conservative, we start with the whole
1990 * visible region but only keep what used to be covered by
1991 * something -- which mean it may have been exposed.
1992 *
1993 * (2) handles areas that were not covered by anything but got
1994 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001995 */
Mathias Agopianab028732010-03-16 16:41:46 -07001996 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001997 const Region oldVisibleRegion = layer->visibleRegion;
1998 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001999 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2000 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001 }
2002 dirty.subtractSelf(aboveOpaqueLayers);
2003
2004 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002005 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006
Mathias Agopianab028732010-03-16 16:41:46 -07002007 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002008 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002009
Jesse Halla8026d22012-09-25 13:25:04 -07002010 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002011 layer->setVisibleRegion(visibleRegion);
2012 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002013 layer->setVisibleNonTransparentRegion(
2014 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002015 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016
Mathias Agopian87baae12012-07-31 12:38:26 -07002017 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018}
2019
Mathias Agopian87baae12012-07-31 12:38:26 -07002020void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2021 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002023 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2024 if (hw->getLayerStack() == layerStack) {
2025 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002026 }
2027 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002028}
2029
Dan Stoza6b9454d2014-11-07 16:00:59 -08002030bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ALOGV("handlePageFlip");
2033
Brian Andersond6927fb2016-07-23 23:37:30 -07002034 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002037 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002038
2039 // Store the set of layers that need updates. This set must not change as
2040 // buffers are being latched, as this could result in a deadlock.
2041 // Example: Two producers share the same command stream and:
2042 // 1.) Layer 0 is latched
2043 // 2.) Layer 0 gets a new frame
2044 // 2.) Layer 1 gets a new frame
2045 // 3.) Layer 1 is latched.
2046 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2047 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002048 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002049 if (layer->hasQueuedFrame()) {
2050 frameQueued = true;
2051 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002052 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002053 } else {
2054 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002055 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002056 } else {
2057 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002058 }
Robert Carr2047fae2016-11-28 14:09:09 -08002059 });
2060
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002062 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002063 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002064 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002065 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002066
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002067 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002068
2069 // If we will need to wake up at some time in the future to deal with a
2070 // queued frame that shouldn't be displayed during this vsync period, wake
2071 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002073 signalLayerUpdate();
2074 }
2075
2076 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078}
2079
Mathias Agopianad456f92011-01-13 17:53:01 -08002080void SurfaceFlinger::invalidateHwcGeometry()
2081{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002083}
2084
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002085
Fabien Sanglard830b8472016-11-30 16:35:58 -08002086void SurfaceFlinger::doDisplayComposition(
2087 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002088 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002089{
Dan Stoza71433162014-02-04 16:22:36 -08002090 // We only need to actually compose the display if:
2091 // 1) It is being handled by hardware composer, which may need this to
2092 // keep its virtual display state machine in sync, or
2093 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002094 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002095 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002097 return;
2098 }
2099
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 ALOGV("doDisplayComposition");
2101
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 Region dirtyRegion(inDirtyRegion);
2103
Mathias Agopianb8a55602009-06-26 19:06:36 -07002104 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002105 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106
Fabien Sanglard830b8472016-11-30 16:35:58 -08002107 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002108 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002109 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2110 // takes a rectangle, we must make sure to update that whole
2111 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002112 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002113 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002114 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002115 // We need to redraw the rectangle that will be updated
2116 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002117 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002118 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002119 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002120 } else {
2121 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002122 dirtyRegion.set(displayDevice->bounds());
2123 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124 }
2125 }
2126
Fabien Sanglard830b8472016-11-30 16:35:58 -08002127 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002129 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002130 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002131
2132 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002133 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134}
2135
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136bool SurfaceFlinger::doComposeSurfaces(
2137 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002138{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002139 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002140
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002142
2143 mat4 oldColorMatrix;
2144 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2145 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2146 if (applyColorMatrix) {
2147 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2148 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2149 }
2150
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2152 if (hasClientComposition) {
2153 ALOGV("hasClientComposition");
2154
2155 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002156 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002158 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2159 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2160 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2161 }
2162 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002163 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002164
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002165 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2167 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002168 // when using overlays, we assume a fully transparent framebuffer
2169 // NOTE: we could reduce how much we need to clear, for instance
2170 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002171 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002172 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002174 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002175 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002177
2178 // we remove the scissor part
2179 // we're left with the letterbox region
2180 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002182
2183 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002185
2186 // but limit it to the dirty region
2187 region.andSelf(dirty);
2188
Mathias Agopianb9494d52012-04-18 02:28:45 -07002189 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002190 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002191 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002193 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002194 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002195
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002197 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002198 // scissor on the main display. It should never be needed
2199 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002200 const Rect& bounds(displayDevice->getBounds());
2201 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002202 if (scissor != bounds) {
2203 // scissor doesn't match the screen's dimensions, so we
2204 // need to clear everything outside of it and enable
2205 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002206
Mathias Agopianf45c5102012-10-24 16:29:17 -07002207 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 const uint32_t height = displayDevice->getHeight();
2209 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002210 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002211 }
2212 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002213 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002214
Mathias Agopian85d751c2012-08-29 16:59:24 -07002215 /*
2216 * and then, render the layers targeted at the framebuffer
2217 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002218
Dan Stoza9e56aa02015-11-02 13:00:03 -08002219 ALOGV("Rendering client layers");
2220 const Transform& displayTransform = displayDevice->getTransform();
2221 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002222 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002223 bool firstLayer = true;
2224 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2225 const Region clip(dirty.intersect(
2226 displayTransform.transform(layer->visibleRegion)));
2227 ALOGV("Layer: %s", layer->getName().string());
2228 ALOGV(" Composition type: %s",
2229 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002230 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 switch (layer->getCompositionType(hwcId)) {
2232 case HWC2::Composition::Cursor:
2233 case HWC2::Composition::Device:
2234 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002235 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2237 layer->isOpaque(state) && (state.alpha == 1.0f)
2238 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002239 // never clear the very first layer since we're
2240 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002241 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002242 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002243 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002244 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002245 case HWC2::Composition::Client: {
2246 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002247 break;
2248 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002250 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002251 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 } else {
2253 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002254 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002255 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002256 }
2257 } else {
2258 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002260 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002261 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002262 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002263 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002264 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002265 }
2266 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002267
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002268 if (applyColorMatrix) {
2269 getRenderEngine().setupColorTransform(oldColorMatrix);
2270 }
2271
Mathias Agopianf45c5102012-10-24 16:29:17 -07002272 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002274 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002275}
2276
Fabien Sanglard830b8472016-11-30 16:35:58 -08002277void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2278 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002279 RenderEngine& engine(getRenderEngine());
2280 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281}
2282
Dan Stoza7d89d062015-04-30 13:29:25 -07002283status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002284 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002285 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002286 const sp<Layer>& lbc,
2287 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002288{
Dan Stoza7d89d062015-04-30 13:29:25 -07002289 // add this layer to the current state list
2290 {
2291 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002292 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002293 return NO_MEMORY;
2294 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002295 if (parent == nullptr) {
2296 mCurrentState.layersSortedByZ.add(lbc);
2297 } else {
2298 parent->addChild(lbc);
2299 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002300 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 mLayersAdded = true;
2302 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002303 }
2304
Mathias Agopian96f08192010-06-02 23:28:45 -07002305 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002306 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002307
Dan Stoza7d89d062015-04-30 13:29:25 -07002308 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002309}
2310
Dan Stoza22851c32016-08-09 13:21:03 -07002311status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002313 sp<Layer> layer = weakLayer.promote();
2314 if (layer == nullptr) {
2315 // The layer has already been removed, carry on
2316 return NO_ERROR;
2317 }
2318
Robert Carr1f0a16a2016-10-24 16:27:39 -07002319 const auto& p = layer->getParent();
2320 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2321 mCurrentState.layersSortedByZ.remove(layer);
2322
2323 if (index < 0) {
2324 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2325 layer->getName().string(),
2326 (p != nullptr) ? p->getName().string() : "no-parent");
2327 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002328 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002329
2330 mLayersPendingRemoval.add(layer);
2331 mLayersRemoved = true;
2332 mNumLayers--;
2333 setTransactionFlags(eTransactionNeeded);
2334 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335}
2336
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002337uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002338 return android_atomic_release_load(&mTransactionFlags);
2339}
2340
Mathias Agopian3f844832013-08-07 21:24:32 -07002341uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2343}
2344
Mathias Agopian3f844832013-08-07 21:24:32 -07002345uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2347 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002348 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 }
2350 return old;
2351}
2352
Mathias Agopian8b33f032012-07-24 20:43:54 -07002353void SurfaceFlinger::setTransactionState(
2354 const Vector<ComposerState>& state,
2355 const Vector<DisplayState>& displays,
2356 uint32_t flags)
2357{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002358 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002359 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002360 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002361
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002362 if (flags & eAnimation) {
2363 // For window updates that are part of an animation we must wait for
2364 // previous animation "frames" to be handled.
2365 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002366 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002367 if (CC_UNLIKELY(err != NO_ERROR)) {
2368 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002369 // caller after a few seconds.
2370 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2371 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002372 mAnimTransactionPending = false;
2373 break;
2374 }
2375 }
2376 }
2377
Mathias Agopiane57f2922012-08-09 16:29:12 -07002378 size_t count = displays.size();
2379 for (size_t i=0 ; i<count ; i++) {
2380 const DisplayState& s(displays[i]);
2381 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002382 }
2383
Mathias Agopiane57f2922012-08-09 16:29:12 -07002384 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002385 for (size_t i=0 ; i<count ; i++) {
2386 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002387 // Here we need to check that the interface we're given is indeed
2388 // one of our own. A malicious client could give us a NULL
2389 // IInterface, or one of its own or even one of our own but a
2390 // different type. All these situations would cause us to crash.
2391 //
2392 // NOTE: it would be better to use RTTI as we could directly check
2393 // that we have a Client*. however, RTTI is disabled in Android.
2394 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002395 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002396 if (binder != NULL) {
2397 String16 desc(binder->getInterfaceDescriptor());
2398 if (desc == ISurfaceComposerClient::descriptor) {
2399 sp<Client> client( static_cast<Client *>(s.client.get()) );
2400 transactionFlags |= setClientStateLocked(client, s.state);
2401 }
2402 }
2403 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002404 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002405
Robert Carr2a7dbb42016-05-24 11:41:28 -07002406 // If a synchronous transaction is explicitly requested without any changes,
2407 // force a transaction anyway. This can be used as a flush mechanism for
2408 // previous async transactions.
2409 if (transactionFlags == 0 && (flags & eSynchronous)) {
2410 transactionFlags = eTransactionNeeded;
2411 }
2412
Mathias Agopian386aa982011-11-07 21:58:03 -08002413 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002414 if (mInterceptor.isEnabled()) {
2415 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2416 }
Irvel468051e2016-06-13 16:44:44 -07002417
Mathias Agopian386aa982011-11-07 21:58:03 -08002418 // this triggers the transaction
2419 setTransactionFlags(transactionFlags);
2420
2421 // if this is a synchronous transaction, wait for it to take effect
2422 // before returning.
2423 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002424 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002425 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002426 if (flags & eAnimation) {
2427 mAnimTransactionPending = true;
2428 }
2429 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002430 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2431 if (CC_UNLIKELY(err != NO_ERROR)) {
2432 // just in case something goes wrong in SF, return to the
2433 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002434 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2435 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002436 break;
2437 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 }
2440}
2441
Mathias Agopiane57f2922012-08-09 16:29:12 -07002442uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2443{
Jesse Hall9a143922012-10-04 16:29:19 -07002444 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2445 if (dpyIdx < 0)
2446 return 0;
2447
Mathias Agopiane57f2922012-08-09 16:29:12 -07002448 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002449 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002450 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002451 const uint32_t what = s.what;
2452 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002453 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 disp.surface = s.surface;
2455 flags |= eDisplayTransactionNeeded;
2456 }
2457 }
2458 if (what & DisplayState::eLayerStackChanged) {
2459 if (disp.layerStack != s.layerStack) {
2460 disp.layerStack = s.layerStack;
2461 flags |= eDisplayTransactionNeeded;
2462 }
2463 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002464 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002465 if (disp.orientation != s.orientation) {
2466 disp.orientation = s.orientation;
2467 flags |= eDisplayTransactionNeeded;
2468 }
2469 if (disp.frame != s.frame) {
2470 disp.frame = s.frame;
2471 flags |= eDisplayTransactionNeeded;
2472 }
2473 if (disp.viewport != s.viewport) {
2474 disp.viewport = s.viewport;
2475 flags |= eDisplayTransactionNeeded;
2476 }
2477 }
Michael Lentine47e45402014-07-18 15:34:25 -07002478 if (what & DisplayState::eDisplaySizeChanged) {
2479 if (disp.width != s.width) {
2480 disp.width = s.width;
2481 flags |= eDisplayTransactionNeeded;
2482 }
2483 if (disp.height != s.height) {
2484 disp.height = s.height;
2485 flags |= eDisplayTransactionNeeded;
2486 }
2487 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002488 }
2489 return flags;
2490}
2491
2492uint32_t SurfaceFlinger::setClientStateLocked(
2493 const sp<Client>& client,
2494 const layer_state_t& s)
2495{
2496 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002497 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002498 if (layer != 0) {
2499 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002500 bool geometryAppliesWithResize =
2501 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002502 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002503 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002504 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002505 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002506 }
2507 if (what & layer_state_t::eLayerChanged) {
2508 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 const auto& p = layer->getParent();
2510 if (p == nullptr) {
2511 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2512 if (layer->setLayer(s.z) && idx >= 0) {
2513 mCurrentState.layersSortedByZ.removeAt(idx);
2514 mCurrentState.layersSortedByZ.add(layer);
2515 // we need traversal (state changed)
2516 // AND transaction (list changed)
2517 flags |= eTransactionNeeded|eTraversalNeeded;
2518 }
2519 } else {
2520 if (p->setChildLayer(layer, s.z)) {
2521 flags |= eTransactionNeeded|eTraversalNeeded;
2522 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002523 }
2524 }
2525 if (what & layer_state_t::eSizeChanged) {
2526 if (layer->setSize(s.w, s.h)) {
2527 flags |= eTraversalNeeded;
2528 }
2529 }
2530 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002532 flags |= eTraversalNeeded;
2533 }
2534 if (what & layer_state_t::eMatrixChanged) {
2535 if (layer->setMatrix(s.matrix))
2536 flags |= eTraversalNeeded;
2537 }
2538 if (what & layer_state_t::eTransparentRegionChanged) {
2539 if (layer->setTransparentRegionHint(s.transparentRegion))
2540 flags |= eTraversalNeeded;
2541 }
Dan Stoza23116082015-06-18 14:58:39 -07002542 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002543 if (layer->setFlags(s.flags, s.mask))
2544 flags |= eTraversalNeeded;
2545 }
2546 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002547 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002548 flags |= eTraversalNeeded;
2549 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002550 if (what & layer_state_t::eFinalCropChanged) {
2551 if (layer->setFinalCrop(s.finalCrop))
2552 flags |= eTraversalNeeded;
2553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002554 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002555 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002556 // We only allow setting layer stacks for top level layers,
2557 // everything else inherits layer stack from its parent.
2558 if (layer->hasParent()) {
2559 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2560 layer->getName().string());
2561 } else if (idx < 0) {
2562 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2563 "that also does not appear in the top level layer list. Something"
2564 " has gone wrong.", layer->getName().string());
2565 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 mCurrentState.layersSortedByZ.removeAt(idx);
2567 mCurrentState.layersSortedByZ.add(layer);
2568 // we need traversal (state changed)
2569 // AND transaction (list changed)
2570 flags |= eTransactionNeeded|eTraversalNeeded;
2571 }
2572 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002573 if (what & layer_state_t::eDeferTransaction) {
2574 layer->deferTransactionUntil(s.handle, s.frameNumber);
2575 // We don't trigger a traversal here because if no other state is
2576 // changed, we don't want this to cause any more work
2577 }
Robert Carrc3574f72016-03-24 12:19:32 -07002578 if (what & layer_state_t::eOverrideScalingModeChanged) {
2579 layer->setOverrideScalingMode(s.overrideScalingMode);
2580 // We don't trigger a traversal here because if no other state is
2581 // changed, we don't want this to cause any more work
2582 }
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05002583 if (what & layer_state_t::eLayerInfoChanged) {
2584 layer->setInfo(s.type, s.appid);
2585 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002586 }
2587 return flags;
2588}
2589
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002590status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002591 const String8& name,
2592 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002593 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
2595 sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002597 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002598 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002599 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002600 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002601 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002602
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002603 status_t result = NO_ERROR;
2604
2605 sp<Layer> layer;
2606
Mathias Agopian3165cc22012-08-08 19:42:09 -07002607 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2608 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002609 result = createNormalLayer(client,
2610 name, w, h, flags, format,
2611 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002613 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002614 result = createDimLayer(client,
2615 name, w, h, flags,
2616 handle, gbp, &layer);
2617 break;
2618 default:
2619 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 break;
2621 }
2622
Dan Stoza7d89d062015-04-30 13:29:25 -07002623 if (result != NO_ERROR) {
2624 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002626
Robert Carr1f0a16a2016-10-24 16:27:39 -07002627 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002628 if (result != NO_ERROR) {
2629 return result;
2630 }
Irvelffc9efc2016-07-27 15:16:37 -07002631 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002632
2633 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002634 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635}
2636
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002637status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2638 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2639 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640{
2641 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002642 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 case PIXEL_FORMAT_TRANSPARENT:
2644 case PIXEL_FORMAT_TRANSLUCENT:
2645 format = PIXEL_FORMAT_RGBA_8888;
2646 break;
2647 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002648 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649 break;
2650 }
2651
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002652 *outLayer = new Layer(this, client, name, w, h, flags);
2653 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2654 if (err == NO_ERROR) {
2655 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002656 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002658
2659 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2660 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002663status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2664 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2665 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002667 *outLayer = new LayerDim(this, client, name, w, h, flags);
2668 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002669 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002670 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002671}
2672
Mathias Agopianac9fa422013-02-11 16:40:36 -08002673status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674{
Mathias Agopian67106042013-03-14 19:18:13 -07002675 // called by the window manager when it wants to remove a Layer
2676 status_t err = NO_ERROR;
2677 sp<Layer> l(client->getLayerUser(handle));
2678 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002679 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002680 err = removeLayer(l);
2681 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2682 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002683 }
2684 return err;
2685}
2686
Mathias Agopian13127d82013-03-05 17:47:11 -08002687status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002688{
Mathias Agopian67106042013-03-14 19:18:13 -07002689 // called by ~LayerCleaner() when all references to the IBinder (handle)
2690 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002691 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692}
2693
Mathias Agopianb60314a2012-04-10 22:09:54 -07002694// ---------------------------------------------------------------------------
2695
Andy McFadden13a082e2012-08-24 10:16:42 -07002696void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002697 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002698 Vector<ComposerState> state;
2699 Vector<DisplayState> displays;
2700 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002701 d.what = DisplayState::eDisplayProjectionChanged |
2702 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002703 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002704 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002705 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002706 d.frame.makeInvalid();
2707 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002708 d.width = 0;
2709 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002710 displays.add(d);
2711 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002712 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002713
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2715 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002716 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002717}
2718
2719void SurfaceFlinger::initializeDisplays() {
2720 class MessageScreenInitialized : public MessageBase {
2721 SurfaceFlinger* flinger;
2722 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002723 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002724 virtual bool handler() {
2725 flinger->onInitializeDisplays();
2726 return true;
2727 }
2728 };
2729 sp<MessageBase> msg = new MessageScreenInitialized(this);
2730 postMessageAsync(msg); // we may be called from main thread, use async message
2731}
2732
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002733void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2734 int mode) {
2735 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2736 this);
2737 int32_t type = hw->getDisplayType();
2738 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002739
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002740 if (mode == currentMode) {
2741 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002742 return;
2743 }
2744
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002745 hw->setPowerMode(mode);
2746 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2747 ALOGW("Trying to set power mode for virtual display");
2748 return;
2749 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002750
Irvelffc9efc2016-07-27 15:16:37 -07002751 if (mInterceptor.isEnabled()) {
2752 Mutex::Autolock _l(mStateLock);
2753 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2754 if (idx < 0) {
2755 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2756 return;
2757 }
2758 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2759 }
2760
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002761 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002762 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002763 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002764 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2765 // FIXME: eventthread only knows about the main display right now
2766 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002767 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002768 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002770 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002771 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002772 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002773
2774 struct sched_param param = {0};
2775 param.sched_priority = 1;
2776 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2777 ALOGW("Couldn't set SCHED_FIFO on display on");
2778 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002779 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002780 // Turn off the display
2781 struct sched_param param = {0};
2782 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2783 ALOGW("Couldn't set SCHED_OTHER on display off");
2784 }
2785
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002786 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002787 disableHardwareVsync(true); // also cancels any in-progress resync
2788
Mathias Agopiancde87a32012-09-13 14:09:01 -07002789 // FIXME: eventthread only knows about the main display right now
2790 mEventThread->onScreenReleased();
2791 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002792
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002793 getHwComposer().setPowerMode(type, mode);
2794 mVisibleRegionsDirty = true;
2795 // from this point on, SF will stop drawing on this display
2796 } else {
2797 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002798 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002799}
2800
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002801void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2802 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002803 SurfaceFlinger& mFlinger;
2804 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002805 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002806 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002807 MessageSetPowerMode(SurfaceFlinger& flinger,
2808 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2809 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002810 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002811 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002812 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002813 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002814 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002815 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002816 ALOGW("Attempt to set power mode = %d for virtual display",
2817 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002818 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002819 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002820 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002821 return true;
2822 }
2823 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002824 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002825 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002826}
2827
2828// ---------------------------------------------------------------------------
2829
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2831{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002833
Mathias Agopianbd115332013-04-18 16:41:04 -07002834 IPCThreadState* ipc = IPCThreadState::self();
2835 const int pid = ipc->getCallingPid();
2836 const int uid = ipc->getCallingUid();
2837 if ((uid != AID_SHELL) &&
2838 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002839 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002840 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002842 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002843 // (this would indicate SF is stuck, but we want to be able to
2844 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002845 status_t err = mStateLock.timedLock(s2ns(1));
2846 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002847 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002848 result.appendFormat(
2849 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2850 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002851 }
2852
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002853 bool dumpAll = true;
2854 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002855 size_t numArgs = args.size();
2856 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002857 if ((index < numArgs) &&
2858 (args[index] == String16("--list"))) {
2859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002860 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002861 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002862 }
2863
2864 if ((index < numArgs) &&
2865 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002866 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002867 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002868 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002869 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002870
2871 if ((index < numArgs) &&
2872 (args[index] == String16("--latency-clear"))) {
2873 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002874 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002875 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002876 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002877
2878 if ((index < numArgs) &&
2879 (args[index] == String16("--dispsync"))) {
2880 index++;
2881 mPrimaryDispSync.dump(result);
2882 dumpAll = false;
2883 }
Dan Stozab90cf072015-03-05 11:05:59 -08002884
2885 if ((index < numArgs) &&
2886 (args[index] == String16("--static-screen"))) {
2887 index++;
2888 dumpStaticScreenStats(result);
2889 dumpAll = false;
2890 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002891
2892 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002893 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002894 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002895 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002896 dumpAll = false;
2897 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002899
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002900 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002901 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002902 }
2903
Mathias Agopian9795c422009-08-26 16:36:26 -07002904 if (locked) {
2905 mStateLock.unlock();
2906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 }
2908 write(fd, result.string(), result.size());
2909 return NO_ERROR;
2910}
2911
Dan Stozac7014012014-02-14 15:03:43 -08002912void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2913 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002914{
Robert Carr2047fae2016-11-28 14:09:09 -08002915 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002916 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002917 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002918}
2919
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002920void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002921 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002922{
2923 String8 name;
2924 if (index < args.size()) {
2925 name = String8(args[index]);
2926 index++;
2927 }
2928
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2930 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002931 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002932
2933 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002934 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002935 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002936 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002937 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002938 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002939 }
Robert Carr2047fae2016-11-28 14:09:09 -08002940 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002941 }
2942}
2943
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002944void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002945 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002946{
2947 String8 name;
2948 if (index < args.size()) {
2949 name = String8(args[index]);
2950 index++;
2951 }
2952
Robert Carr2047fae2016-11-28 14:09:09 -08002953 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002954 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002955 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002956 }
Robert Carr2047fae2016-11-28 14:09:09 -08002957 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002958
Svetoslavd85084b2014-03-20 10:28:31 -07002959 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002960}
2961
Jamie Gennis6547ff42013-07-16 20:12:42 -07002962// This should only be called from the main thread. Otherwise it would need
2963// the lock and should use mCurrentState rather than mDrawingState.
2964void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002965 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07002966 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002967 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07002968
2969 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2970}
2971
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002972void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07002973{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002974 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07002975#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002976 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07002977#endif
2978#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002979 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07002980#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002981 if (isLayerTripleBufferingDisabled())
2982 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002983 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07002984}
2985
Dan Stozab90cf072015-03-05 11:05:59 -08002986void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2987{
2988 result.appendFormat("Static screen stats:\n");
2989 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2990 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2991 float percent = 100.0f *
2992 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2993 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2994 b + 1, bucketTimeSec, percent);
2995 }
2996 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2997 float percent = 100.0f *
2998 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2999 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3000 NUM_BUCKETS - 1, bucketTimeSec, percent);
3001}
3002
Dan Stozae77c7662016-05-13 11:37:28 -07003003void SurfaceFlinger::recordBufferingStats(const char* layerName,
3004 std::vector<OccupancyTracker::Segment>&& history) {
3005 Mutex::Autolock lock(mBufferingStatsMutex);
3006 auto& stats = mBufferingStats[layerName];
3007 for (const auto& segment : history) {
3008 if (!segment.usedThirdBuffer) {
3009 stats.twoBufferTime += segment.totalTime;
3010 }
3011 if (segment.occupancyAverage < 1.0f) {
3012 stats.doubleBufferedTime += segment.totalTime;
3013 } else if (segment.occupancyAverage < 2.0f) {
3014 stats.tripleBufferedTime += segment.totalTime;
3015 }
3016 ++stats.numSegments;
3017 stats.totalTime += segment.totalTime;
3018 }
3019}
3020
Brian Andersond6927fb2016-07-23 23:37:30 -07003021void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3022 result.appendFormat("Layer frame timestamps:\n");
3023
3024 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3025 const size_t count = currentLayers.size();
3026 for (size_t i=0 ; i<count ; i++) {
3027 currentLayers[i]->dumpFrameEvents(result);
3028 }
3029}
3030
Dan Stozae77c7662016-05-13 11:37:28 -07003031void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3032 result.append("Buffering stats:\n");
3033 result.append(" [Layer name] <Active time> <Two buffer> "
3034 "<Double buffered> <Triple buffered>\n");
3035 Mutex::Autolock lock(mBufferingStatsMutex);
3036 typedef std::tuple<std::string, float, float, float> BufferTuple;
3037 std::map<float, BufferTuple, std::greater<float>> sorted;
3038 for (const auto& statsPair : mBufferingStats) {
3039 const char* name = statsPair.first.c_str();
3040 const BufferingStats& stats = statsPair.second;
3041 if (stats.numSegments == 0) {
3042 continue;
3043 }
3044 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3045 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3046 stats.totalTime;
3047 float doubleBufferRatio = static_cast<float>(
3048 stats.doubleBufferedTime) / stats.totalTime;
3049 float tripleBufferRatio = static_cast<float>(
3050 stats.tripleBufferedTime) / stats.totalTime;
3051 sorted.insert({activeTime, {name, twoBufferRatio,
3052 doubleBufferRatio, tripleBufferRatio}});
3053 }
3054 for (const auto& sortedPair : sorted) {
3055 float activeTime = sortedPair.first;
3056 const BufferTuple& values = sortedPair.second;
3057 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3058 std::get<0>(values).c_str(), activeTime,
3059 std::get<1>(values), std::get<2>(values),
3060 std::get<3>(values));
3061 }
3062 result.append("\n");
3063}
3064
3065
Mathias Agopian74d211a2013-04-22 16:55:35 +02003066void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3067 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003068{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003069 bool colorize = false;
3070 if (index < args.size()
3071 && (args[index] == String16("--color"))) {
3072 colorize = true;
3073 index++;
3074 }
3075
3076 Colorizer colorizer(colorize);
3077
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003078 // figure out if we're stuck somewhere
3079 const nsecs_t now = systemTime();
3080 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3081 const nsecs_t inTransaction(mDebugInTransaction);
3082 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3083 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3084
3085 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003086 * Dump library configuration.
3087 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003088
3089 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003090 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003092 appendSfConfigString(result);
3093 appendUiConfigString(result);
3094 appendGuiConfigString(result);
3095 result.append("\n");
3096
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003097 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003098 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003099 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003100 result.append(SyncFeatures::getInstance().toString());
3101 result.append("\n");
3102
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3104
Andy McFadden41d67d72014-04-25 16:58:34 -07003105 colorizer.bold(result);
3106 result.append("DispSync configuration: ");
3107 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003108 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3109 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003110 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3111 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003112 result.append("\n");
3113
Dan Stozab90cf072015-03-05 11:05:59 -08003114 // Dump static screen stats
3115 result.append("\n");
3116 dumpStaticScreenStats(result);
3117 result.append("\n");
3118
Dan Stozae77c7662016-05-13 11:37:28 -07003119 dumpBufferingStats(result);
3120
Andy McFadden4803b742012-09-24 19:07:20 -07003121 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003122 * Dump the visible layer list
3123 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003124 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003126 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003127 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003128 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003129 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003130
3131 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003132 * Dump Display state
3133 */
3134
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003135 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003136 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003137 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003138 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3139 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003140 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003141 }
3142
3143 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003144 * Dump SurfaceFlinger global state
3145 */
3146
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003147 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003148 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003149 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150
Mathias Agopian888c8222012-08-04 21:10:38 -07003151 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003152 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003153
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003154 colorizer.bold(result);
3155 result.appendFormat("EGL implementation : %s\n",
3156 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3157 colorizer.reset(result);
3158 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003159 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003160
Mathias Agopian875d8e12013-06-07 15:35:48 -07003161 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003162
Mathias Agopian42977342012-08-05 00:40:46 -07003163 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003164 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3165 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003166 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003167 " last eglSwapBuffers() time: %f us\n"
3168 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003169 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170 " refresh-rate : %f fps\n"
3171 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003172 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003173 " gpu_to_cpu_unsupported : %d\n"
3174 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003175 mLastSwapBufferTime/1000.0,
3176 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003177 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003178 1e9 / activeConfig->getVsyncPeriod(),
3179 activeConfig->getDpiX(),
3180 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003181 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003182
Mathias Agopian74d211a2013-04-22 16:55:35 +02003183 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003184 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003185
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003187 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003188
3189 /*
3190 * VSYNC state
3191 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003192 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003193 result.append("\n");
3194
3195 /*
3196 * HWC layer minidump
3197 */
3198 for (size_t d = 0; d < mDisplays.size(); d++) {
3199 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3200 int32_t hwcId = displayDevice->getHwcDisplayId();
3201 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3202 continue;
3203 }
3204
3205 result.appendFormat("Display %d HWC layers:\n", hwcId);
3206 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003208 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003209 });
Dan Stozae22aec72016-08-01 13:20:59 -07003210 result.append("\n");
3211 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003212
3213 /*
3214 * Dump HWComposer state
3215 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003216 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003217 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003218 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003219 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003220 result.appendFormat(" h/w composer %s\n",
3221 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003222 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003223
3224 /*
3225 * Dump gralloc state
3226 */
3227 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3228 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003229}
3230
Mathias Agopian13127d82013-03-05 17:47:11 -08003231const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003232SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003233 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003234 wp<IBinder> dpy;
3235 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3236 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3237 dpy = mDisplays.keyAt(i);
3238 break;
3239 }
3240 }
3241 if (dpy == NULL) {
3242 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3243 // Just use the primary display so we have something to return
3244 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3245 }
3246 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003247}
3248
Keun young Park63f165f2012-08-31 10:53:36 -07003249bool SurfaceFlinger::startDdmConnection()
3250{
3251 void* libddmconnection_dso =
3252 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3253 if (!libddmconnection_dso) {
3254 return false;
3255 }
3256 void (*DdmConnection_start)(const char* name);
3257 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003258 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003259 if (!DdmConnection_start) {
3260 dlclose(libddmconnection_dso);
3261 return false;
3262 }
3263 (*DdmConnection_start)(getServiceName());
3264 return true;
3265}
3266
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003267status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 switch (code) {
3269 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003270 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003271 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003273 case CLEAR_ANIMATION_FRAME_STATS:
3274 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003275 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003276 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 {
3278 // codes that require permission check
3279 IPCThreadState* ipc = IPCThreadState::self();
3280 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003281 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003282 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003283 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003284 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003285 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003287 break;
3288 }
3289 case CAPTURE_SCREEN:
3290 {
3291 // codes that require permission check
3292 IPCThreadState* ipc = IPCThreadState::self();
3293 const int pid = ipc->getCallingPid();
3294 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003295 if ((uid != AID_GRAPHICS) &&
3296 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003297 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003298 return PERMISSION_DENIED;
3299 }
3300 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 }
3302 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003303 return OK;
3304}
3305
3306status_t SurfaceFlinger::onTransact(
3307 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3308{
3309 status_t credentialCheck = CheckTransactCodeCredentials(code);
3310 if (credentialCheck != OK) {
3311 return credentialCheck;
3312 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3315 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003316 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003317 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003318 IPCThreadState* ipc = IPCThreadState::self();
3319 const int pid = ipc->getCallingPid();
3320 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003321 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003322 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 return PERMISSION_DENIED;
3324 }
3325 int n;
3326 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003327 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003328 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 return NO_ERROR;
3330 case 1002: // SHOW_UPDATES
3331 n = data.readInt32();
3332 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003333 invalidateHwcGeometry();
3334 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003337 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003338 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003340 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341 setTransactionFlags(
3342 eTransactionNeeded|
3343 eDisplayTransactionNeeded|
3344 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003345 return NO_ERROR;
3346 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003347 case 1006:{ // send empty update
3348 signalRefresh();
3349 return NO_ERROR;
3350 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003351 case 1008: // toggle use of hw composer
3352 n = data.readInt32();
3353 mDebugDisableHWC = n ? 1 : 0;
3354 invalidateHwcGeometry();
3355 repaintEverything();
3356 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003357 case 1009: // toggle use of transform hint
3358 n = data.readInt32();
3359 mDebugDisableTransformHint = n ? 1 : 0;
3360 invalidateHwcGeometry();
3361 repaintEverything();
3362 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003364 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 reply->writeInt32(0);
3366 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003367 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003368 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369 return NO_ERROR;
3370 case 1013: {
3371 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003372 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3373 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003374 return NO_ERROR;
3375 }
3376 case 1014: {
3377 // daltonize
3378 n = data.readInt32();
3379 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003380 case 1:
3381 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3382 break;
3383 case 2:
3384 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3385 break;
3386 case 3:
3387 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3388 break;
3389 default:
3390 mDaltonizer.setType(ColorBlindnessType::None);
3391 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003392 }
3393 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003394 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003395 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003396 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003397 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003398 invalidateHwcGeometry();
3399 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003400 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003401 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003402 case 1015: {
3403 // apply a color matrix
3404 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003405 if (n) {
3406 // color matrix is sent as mat3 matrix followed by vec3
3407 // offset, then packed into a mat4 where the last row is
3408 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003409 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003410 for (size_t j = 0; j < 4; j++) {
3411 mColorMatrix[i][j] = data.readFloat();
3412 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003413 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003414 } else {
3415 mColorMatrix = mat4();
3416 }
3417 invalidateHwcGeometry();
3418 repaintEverything();
3419 return NO_ERROR;
3420 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003421 // This is an experimental interface
3422 // Needs to be shifted to proper binder interface when we productize
3423 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003424 n = data.readInt32();
3425 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003426 return NO_ERROR;
3427 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003428 case 1017: {
3429 n = data.readInt32();
3430 mForceFullDamage = static_cast<bool>(n);
3431 return NO_ERROR;
3432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003433 case 1018: { // Modify Choreographer's phase offset
3434 n = data.readInt32();
3435 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3436 return NO_ERROR;
3437 }
3438 case 1019: { // Modify SurfaceFlinger's phase offset
3439 n = data.readInt32();
3440 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3441 return NO_ERROR;
3442 }
Irvel468051e2016-06-13 16:44:44 -07003443 case 1020: { // Layer updates interceptor
3444 n = data.readInt32();
3445 if (n) {
3446 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003447 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003448 }
3449 else{
3450 ALOGV("Interceptor disabled");
3451 mInterceptor.disable();
3452 }
3453 return NO_ERROR;
3454 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003455 case 1021: { // Disable HWC virtual displays
3456 n = data.readInt32();
3457 mUseHwcVirtualDisplays = !n;
3458 return NO_ERROR;
3459 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460 }
3461 }
3462 return err;
3463}
3464
Mathias Agopian53331da2011-08-22 21:44:41 -07003465void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003466 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003467 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003468}
3469
Mathias Agopian59119e62010-10-11 12:37:43 -07003470// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003471// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003472// ---------------------------------------------------------------------------
3473
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003474/* The code below is here to handle b/8734824
3475 *
3476 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003477 * from the surfaceflinger thread to the calling binder thread, where they
3478 * are executed. This allows the calling thread in the calling process to be
3479 * reused and not depend on having "enough" binder threads to handle the
3480 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003481 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003482class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003483 /* Parts of GraphicProducerWrapper are run on two different threads,
3484 * communicating by sending messages via Looper but also by shared member
3485 * data. Coherence maintenance is subtle and in places implicit (ugh).
3486 *
3487 * Don't rely on Looper's sendMessage/handleMessage providing
3488 * release/acquire semantics for any data not actually in the Message.
3489 * Data going from surfaceflinger to binder threads needs to be
3490 * synchronized explicitly.
3491 *
3492 * Barrier open/wait do provide release/acquire semantics. This provides
3493 * implicit synchronization for data coming back from binder to
3494 * surfaceflinger threads.
3495 */
3496
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003497 sp<IGraphicBufferProducer> impl;
3498 sp<Looper> looper;
3499 status_t result;
3500 bool exitPending;
3501 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003502 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003503 uint32_t code;
3504 Parcel const* data;
3505 Parcel* reply;
3506
3507 enum {
3508 MSG_API_CALL,
3509 MSG_EXIT
3510 };
3511
3512 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003513 * Called on surfaceflinger thread. This is called by our "fake"
3514 * BpGraphicBufferProducer. We package the data and reply Parcel and
3515 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003516 */
3517 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003518 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003519 this->code = code;
3520 this->data = &data;
3521 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003522 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003523 // if we've exited, we run the message synchronously right here.
3524 // note (JH): as far as I can tell from looking at the code, this
3525 // never actually happens. if it does, i'm not sure if it happens
3526 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003527 handleMessage(Message(MSG_API_CALL));
3528 } else {
3529 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003530 // Prevent stores to this->{code, data, reply} from being
3531 // reordered later than the construction of Message.
3532 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533 looper->sendMessage(this, Message(MSG_API_CALL));
3534 barrier.wait();
3535 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003536 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003537 }
3538
3539 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003540 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003541 * call the real BpGraphicBufferProducer.
3542 */
3543 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003544 int what = message.what;
3545 // Prevent reads below from happening before the read from Message
3546 atomic_thread_fence(memory_order_acquire);
3547 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003548 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003549 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003550 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003551 exitRequested = true;
3552 }
3553 }
3554
3555public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003556 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003557 : impl(impl),
3558 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003559 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003560 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003561 exitRequested(false),
3562 code(0),
3563 data(NULL),
3564 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003565 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003566
Jesse Hallb154c422014-07-13 12:47:02 -07003567 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003568 status_t waitForResponse() {
3569 do {
3570 looper->pollOnce(-1);
3571 } while (!exitRequested);
3572 return result;
3573 }
3574
Jesse Hallb154c422014-07-13 12:47:02 -07003575 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003576 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003577 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003578 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003579 // Ensure this->result is visible to the binder thread before it
3580 // handles the message.
3581 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003582 looper->sendMessage(this, Message(MSG_EXIT));
3583 }
3584};
3585
3586
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003587status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3588 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003589 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003590 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003591 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003592
3593 if (CC_UNLIKELY(display == 0))
3594 return BAD_VALUE;
3595
3596 if (CC_UNLIKELY(producer == 0))
3597 return BAD_VALUE;
3598
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003599 // if we have secure windows on this display, never allow the screen capture
3600 // unless the producer interface is local (i.e.: we can take a screenshot for
3601 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003602 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003603
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003604 // Convert to surfaceflinger's internal rotation type.
3605 Transform::orientation_flags rotationFlags;
3606 switch (rotation) {
3607 case ISurfaceComposer::eRotateNone:
3608 rotationFlags = Transform::ROT_0;
3609 break;
3610 case ISurfaceComposer::eRotate90:
3611 rotationFlags = Transform::ROT_90;
3612 break;
3613 case ISurfaceComposer::eRotate180:
3614 rotationFlags = Transform::ROT_180;
3615 break;
3616 case ISurfaceComposer::eRotate270:
3617 rotationFlags = Transform::ROT_270;
3618 break;
3619 default:
3620 rotationFlags = Transform::ROT_0;
3621 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3622 break;
3623 }
3624
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003625 class MessageCaptureScreen : public MessageBase {
3626 SurfaceFlinger* flinger;
3627 sp<IBinder> display;
3628 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003629 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003630 uint32_t reqWidth, reqHeight;
3631 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003632 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003633 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003634 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003635 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003636 public:
3637 MessageCaptureScreen(SurfaceFlinger* flinger,
3638 const sp<IBinder>& display,
3639 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003640 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003641 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003642 bool useIdentityTransform,
3643 Transform::orientation_flags rotation,
3644 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003645 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003646 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003647 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003648 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003649 rotation(rotation), result(PERMISSION_DENIED),
3650 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003651 {
3652 }
3653 status_t getResult() const {
3654 return result;
3655 }
3656 virtual bool handler() {
3657 Mutex::Autolock _l(flinger->mStateLock);
3658 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003659 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003660 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003661 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003662 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003663 return true;
3664 }
3665 };
3666
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003667 // this creates a "fake" BBinder which will serve as a "fake" remote
3668 // binder to receive the marshaled calls and forward them to the
3669 // real remote (a BpGraphicBufferProducer)
3670 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3671
3672 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3673 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003674 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003675 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003676 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003677 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003678
3679 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003680 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003681 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003682 }
3683 return res;
3684}
3685
Mathias Agopian180f10d2013-04-10 22:55:41 -07003686
3687void SurfaceFlinger::renderScreenImplLocked(
3688 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003689 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003690 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003691 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003692{
3693 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003694 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003695
3696 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003697 const int32_t hw_w = hw->getWidth();
3698 const int32_t hw_h = hw->getHeight();
3699 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003700 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003701
Dan Stozac1879002014-05-22 15:59:05 -07003702 // if a default or invalid sourceCrop is passed in, set reasonable values
3703 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3704 !sourceCrop.isValid()) {
3705 sourceCrop.setLeftTop(Point(0, 0));
3706 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3707 }
3708
3709 // ensure that sourceCrop is inside screen
3710 if (sourceCrop.left < 0) {
3711 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3712 }
Dan Stozabe31f442014-06-11 11:20:54 -07003713 if (sourceCrop.right > hw_w) {
3714 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003715 }
3716 if (sourceCrop.top < 0) {
3717 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3718 }
Dan Stozabe31f442014-06-11 11:20:54 -07003719 if (sourceCrop.bottom > hw_h) {
3720 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003721 }
3722
Mathias Agopian180f10d2013-04-10 22:55:41 -07003723 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003724 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003725
3726 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003727 engine.setViewportAndProjection(
3728 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003729 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003730
3731 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003732 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003733
Robert Carr1f0a16a2016-10-24 16:27:39 -07003734 // We loop through the first level of layers without traversing,
3735 // as we need to interpret min/max layer Z in the top level Z space.
3736 for (const auto& layer : mDrawingState.layersSortedByZ) {
3737 if (layer->getLayerStack() != hw->getLayerStack()) {
3738 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003739 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003740 const Layer::State& state(layer->getDrawingState());
3741 if (state.z < minLayerZ || state.z > maxLayerZ) {
3742 continue;
3743 }
3744 layer->traverseInZOrder([&](Layer* layer) {
3745 if (!layer->isVisible()) {
3746 return;
3747 }
3748 if (filtering) layer->setFiltering(true);
3749 layer->draw(hw, useIdentityTransform);
3750 if (filtering) layer->setFiltering(false);
3751 });
3752 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003753
Mathias Agopian931bda12013-08-28 18:11:46 -07003754 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003755}
3756
3757
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003758status_t SurfaceFlinger::captureScreenImplLocked(
3759 const sp<const DisplayDevice>& hw,
3760 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003761 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003762 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003763 bool useIdentityTransform, Transform::orientation_flags rotation,
3764 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003765{
3766 ATRACE_CALL();
3767
Mathias Agopian180f10d2013-04-10 22:55:41 -07003768 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003769 uint32_t hw_w = hw->getWidth();
3770 uint32_t hw_h = hw->getHeight();
3771
3772 if (rotation & Transform::ROT_90) {
3773 std::swap(hw_w, hw_h);
3774 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003775
Mathias Agopian180f10d2013-04-10 22:55:41 -07003776 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3777 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3778 reqWidth, reqHeight, hw_w, hw_h);
3779 return BAD_VALUE;
3780 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003781
Mathias Agopian180f10d2013-04-10 22:55:41 -07003782 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3783 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3784
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003785 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003786 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003787 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003788 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3789 (state.z < minLayerZ || state.z > maxLayerZ)) {
3790 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003791 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003792 layer->traverseInZOrder([&](Layer *layer) {
3793 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3794 layer->isSecure());
3795 });
3796 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003797
3798 if (!isLocalScreenshot && secureLayerIsVisible) {
3799 ALOGW("FB is protected: PERMISSION_DENIED");
3800 return PERMISSION_DENIED;
3801 }
3802
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003803 // create a surface (because we're a producer, and we need to
3804 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003805 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003806
3807 // Put the screenshot Surface into async mode so that
3808 // Layer::headFenceHasSignaled will always return true and we'll latch the
3809 // first buffer regardless of whether or not its acquire fence has
3810 // signaled. This is needed to avoid a race condition in the rotation
3811 // animation. See b/30209608
3812 sur->setAsyncMode(true);
3813
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003814 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003815
Michael Lentine5a16a622015-05-21 13:48:24 -07003816 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3817 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003818 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3819 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003820
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003821 int err = 0;
3822 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003823 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003824 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3825 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003826
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003827 if (err == NO_ERROR) {
3828 ANativeWindowBuffer* buffer;
3829 /* TODO: Once we have the sync framework everywhere this can use
3830 * server-side waits on the fence that dequeueBuffer returns.
3831 */
3832 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3833 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003834 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003835 // create an EGLImage from the buffer so we can later
3836 // turn it into a texture
3837 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3838 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3839 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003840 // this binds the given EGLImage as a framebuffer for the
3841 // duration of this scope.
3842 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3843 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003844 // this will in fact render into our dequeued buffer
3845 // via an FBO, which means we didn't have to create
3846 // an EGLSurface and therefore we're not
3847 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003848 renderScreenImplLocked(
3849 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3850 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003851
Riley Andrews86639902014-08-15 12:27:24 -07003852 // Attempt to create a sync khr object that can produce a sync point. If that
3853 // isn't available, create a non-dupable sync object in the fallback path and
3854 // wait on it directly.
3855 EGLSyncKHR sync;
3856 if (!DEBUG_SCREENSHOTS) {
3857 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003858 // native fence fd will not be populated until flush() is done.
3859 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003860 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003861 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003862 }
Riley Andrews86639902014-08-15 12:27:24 -07003863 if (sync != EGL_NO_SYNC_KHR) {
3864 // get the sync fd
3865 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3866 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3867 ALOGW("captureScreen: failed to dup sync khr object");
3868 syncFd = -1;
3869 }
3870 eglDestroySyncKHR(mEGLDisplay, sync);
3871 } else {
3872 // fallback path
3873 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3874 if (sync != EGL_NO_SYNC_KHR) {
3875 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3876 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3877 EGLint eglErr = eglGetError();
3878 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3879 ALOGW("captureScreen: fence wait timed out");
3880 } else {
3881 ALOGW_IF(eglErr != EGL_SUCCESS,
3882 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3883 }
3884 eglDestroySyncKHR(mEGLDisplay, sync);
3885 } else {
3886 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3887 }
3888 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003889 if (DEBUG_SCREENSHOTS) {
3890 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3891 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3892 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3893 hw, minLayerZ, maxLayerZ);
3894 delete [] pixels;
3895 }
3896
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003897 } else {
3898 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3899 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003900 window->cancelBuffer(window, buffer, syncFd);
3901 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003902 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003903 // destroy our image
3904 eglDestroyImageKHR(mEGLDisplay, image);
3905 } else {
3906 result = BAD_VALUE;
3907 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003908 if (buffer) {
3909 // queueBuffer takes ownership of syncFd
3910 result = window->queueBuffer(window, buffer, syncFd);
3911 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003912 }
3913 } else {
3914 result = BAD_VALUE;
3915 }
3916 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3917 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003918
Mathias Agopian74c40c02010-09-29 13:02:36 -07003919 return result;
3920}
3921
Mathias Agopiand5556842013-09-19 17:08:37 -07003922void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003923 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003924 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003925 for (size_t y=0 ; y<h ; y++) {
3926 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3927 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003928 if (p[x] != 0xFF000000) return;
3929 }
3930 }
3931 ALOGE("*** we just took a black screenshot ***\n"
3932 "requested minz=%d, maxz=%d, layerStack=%d",
3933 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003934
Robert Carr2047fae2016-11-28 14:09:09 -08003935 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003936 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003937 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003938 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3939 state.z <= maxLayerZ) {
3940 layer->traverseInZOrder([&](Layer* layer) {
3941 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3942 layer->isVisible() ? '+' : '-',
3943 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07003944 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003945 i++;
3946 });
3947 }
3948 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07003949 }
3950}
3951
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003952// ---------------------------------------------------------------------------
3953
Robert Carr2047fae2016-11-28 14:09:09 -08003954void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3955 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003956}
3957
Robert Carr2047fae2016-11-28 14:09:09 -08003958void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3959 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003960}
3961
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003963
3964
3965#if defined(__gl_h_)
3966#error "don't include gl/gl.h in this file"
3967#endif
3968
3969#if defined(__gl2_h_)
3970#error "don't include gl2/gl2.h in this file"
3971#endif