blob: f3d31d964f76dd7efb2e184ab4328fa23ec02f0d [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
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
Evgenii Stepanov22819272016-07-14 14:17:24 -070094// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
95// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
96// suppressed and prevents the device from booting.
97#ifndef __has_feature
98#define __has_feature(x) 0
99#endif
100#if __has_feature(address_sanitizer)
101__attribute__((visibility("default")))
102extern "C" const char* __asan_default_options() {
103 return "alloc_dealloc_mismatch=0";
104}
105#endif
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109// This is the phase offset in nanoseconds of the software vsync event
110// relative to the vsync event reported by HWComposer. The software vsync
111// event is when SurfaceFlinger and Choreographer-based applications run each
112// frame.
113//
114// This phase offset allows adjustment of the minimum latency from application
115// wake-up (by Choregographer) time to the time at which the resulting window
116// image is displayed. This value may be either positive (after the HW vsync)
117// or negative (before the HW vsync). Setting it to 0 will result in a
118// minimum latency of two vsync periods because the app and SurfaceFlinger
119// will run just after the HW vsync. Setting it to a positive number will
120// result in the minimum latency being:
121//
122// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
123//
124// Note that reducing this latency makes it more likely for the applications
125// to not have their window content image ready in time. When this happens
126// the latency will end up being an additional vsync period, and animations
127// will hiccup. Therefore, this latency should be tuned somewhat
128// conservatively (or at least with awareness of the trade-off being made).
129static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
132static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700149 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700150 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800152 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800155 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700157 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700158 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700159 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700160 mDebugInSwapBuffers(0),
161 mLastSwapBufferTime(0),
162 mDebugInTransaction(0),
163 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700164 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700165 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700166 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000167 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700168 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700169 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasColorMatrix(false),
171 mHasPoweredOff(false),
172 mFrameBuckets(),
173 mTotalTime(0),
174 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175{
Steve Blocka19954a2012-01-04 20:05:49 +0000176 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177
178 // debugging stuff...
179 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180
Mathias Agopianb4b17302013-03-20 18:36:41 -0700181 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700182 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 property_get("debug.sf.showupdates", value, "0");
185 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700187 property_get("debug.sf.ddms", value, "0");
188 mDebugDDMS = atoi(value);
189 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700190 if (!startDdmConnection()) {
191 // start failed, and DDMS debugging not enabled
192 mDebugDDMS = 0;
193 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700195 ALOGI_IF(mDebugRegion, "showupdates enabled");
196 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700197
198 property_get("debug.sf.disable_backpressure", value, "0");
199 mPropagateBackpressure = !atoi(value);
200 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700201
202 property_get("debug.sf.disable_hwc_vds", value, "0");
203 mUseHwcVirtualDisplays = !atoi(value);
204 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205}
206
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207void SurfaceFlinger::onFirstRef()
208{
209 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800210}
211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212SurfaceFlinger::~SurfaceFlinger()
213{
Mathias Agopiana4912602012-07-12 14:25:33 -0700214 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
215 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
216 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217}
218
Dan Stozac7014012014-02-14 15:03:43 -0800219void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220{
221 // the window manager died on us. prepare its eulogy.
222
Andy McFadden13a082e2012-08-24 10:16:42 -0700223 // restore initial conditions (default device unblank, etc)
224 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800225
226 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700227 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800228}
229
Mathias Agopian7e27f052010-05-28 14:22:23 -0700230sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231{
Mathias Agopian96f08192010-06-02 23:28:45 -0700232 sp<ISurfaceComposerClient> bclient;
233 sp<Client> client(new Client(this));
234 status_t err = client->initCheck();
235 if (err == NO_ERROR) {
236 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 return bclient;
239}
240
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700241sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
242 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700243{
244 class DisplayToken : public BBinder {
245 sp<SurfaceFlinger> flinger;
246 virtual ~DisplayToken() {
247 // no more references, this display must be terminated
248 Mutex::Autolock _l(flinger->mStateLock);
249 flinger->mCurrentState.displays.removeItem(this);
250 flinger->setTransactionFlags(eDisplayTransactionNeeded);
251 }
252 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700253 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700254 : flinger(flinger) {
255 }
256 };
257
258 sp<BBinder> token = new DisplayToken(this);
259
260 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700261 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700262 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700263 mCurrentState.displays.add(token, info);
264
265 return token;
266}
267
Jesse Hall6c913be2013-08-08 12:15:49 -0700268void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
269 Mutex::Autolock _l(mStateLock);
270
271 ssize_t idx = mCurrentState.displays.indexOfKey(display);
272 if (idx < 0) {
273 ALOGW("destroyDisplay: invalid display token");
274 return;
275 }
276
277 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
278 if (!info.isVirtualDisplay()) {
279 ALOGE("destroyDisplay called for non-virtual display");
280 return;
281 }
282
283 mCurrentState.displays.removeItemsAt(idx);
284 setTransactionFlags(eDisplayTransactionNeeded);
285}
286
Jesse Hall692c7232012-11-08 15:41:56 -0800287void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800288 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800289 ALOGW_IF(mBuiltinDisplays[type],
290 "Overwriting display token for display type %d", type);
291 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800292 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700293 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800294 mCurrentState.displays.add(mBuiltinDisplays[type], info);
295}
296
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700298 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
300 return NULL;
301 }
Jesse Hall692c7232012-11-08 15:41:56 -0800302 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700303}
304
Jamie Gennis9a78c902011-01-12 18:30:40 -0800305sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
306{
307 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
308 return gba;
309}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700310
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311void SurfaceFlinger::bootFinished()
312{
313 const nsecs_t now = systemTime();
314 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000315 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700316 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700317
318 // wait patiently for the window manager death
319 const String16 name("window");
320 sp<IBinder> window(defaultServiceManager()->getService(name));
321 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700322 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700323 }
324
325 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700326 // formerly we would just kill the process, but we now ask it to exit so it
327 // can choose where to stop the animation.
328 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700329
330 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
331 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
332 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333}
334
Mathias Agopian3f844832013-08-07 21:24:32 -0700335void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700336 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700337 RenderEngine& engine;
338 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700339 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700340 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
341 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700342 }
343 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700344 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700345 return true;
346 }
347 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700348 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700349}
350
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700351class DispSyncSource : public VSyncSource, private DispSync::Callback {
352public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700353 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000354 const char* name) :
355 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700356 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700357 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000358 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
359 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700360 mDispSync(dispSync),
361 mCallbackMutex(),
362 mCallback(),
363 mVsyncMutex(),
364 mPhaseOffset(phaseOffset),
365 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700366
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 virtual ~DispSyncSource() {}
368
369 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700370 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700371 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000372 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700373 static_cast<DispSync::Callback*>(this));
374 if (err != NO_ERROR) {
375 ALOGE("error registering vsync callback: %s (%d)",
376 strerror(-err), err);
377 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700378 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379 } else {
380 status_t err = mDispSync->removeEventListener(
381 static_cast<DispSync::Callback*>(this));
382 if (err != NO_ERROR) {
383 ALOGE("error unregistering vsync callback: %s (%d)",
384 strerror(-err), err);
385 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700386 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700387 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700388 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389 }
390
391 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700392 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700393 mCallback = callback;
394 }
395
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700396 virtual void setPhaseOffset(nsecs_t phaseOffset) {
397 Mutex::Autolock lock(mVsyncMutex);
398
399 // Normalize phaseOffset to [0, period)
400 auto period = mDispSync->getPeriod();
401 phaseOffset %= period;
402 if (phaseOffset < 0) {
403 // If we're here, then phaseOffset is in (-period, 0). After this
404 // operation, it will be in (0, period)
405 phaseOffset += period;
406 }
407 mPhaseOffset = phaseOffset;
408
409 // If we're not enabled, we don't need to mess with the listeners
410 if (!mEnabled) {
411 return;
412 }
413
414 // Remove the listener with the old offset
415 status_t err = mDispSync->removeEventListener(
416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error unregistering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
421
422 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700424 static_cast<DispSync::Callback*>(this));
425 if (err != NO_ERROR) {
426 ALOGE("error registering vsync callback: %s (%d)",
427 strerror(-err), err);
428 }
429 }
430
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431private:
432 virtual void onDispSyncEvent(nsecs_t when) {
433 sp<VSyncSource::Callback> callback;
434 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 callback = mCallback;
437
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700438 if (mTraceVsync) {
439 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700440 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700441 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 }
443
444 if (callback != NULL) {
445 callback->onVSyncEvent(when);
446 }
447 }
448
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 const char* const mName;
450
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451 int mValue;
452
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700453 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 const String8 mVsyncOnLabel;
455 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700456
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700457 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700458
459 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461
462 Mutex mVsyncMutex; // Protects the following
463 nsecs_t mPhaseOffset;
464 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465};
466
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700467class InjectVSyncSource : public VSyncSource {
468public:
469 InjectVSyncSource() {}
470
471 virtual ~InjectVSyncSource() {}
472
473 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
474 std::lock_guard<std::mutex> lock(mCallbackMutex);
475 mCallback = callback;
476 }
477
478 virtual void onInjectSyncEvent(nsecs_t when) {
479 std::lock_guard<std::mutex> lock(mCallbackMutex);
480 mCallback->onVSyncEvent(when);
481 }
482
483 virtual void setVSyncEnabled(bool) {}
484 virtual void setPhaseOffset(nsecs_t) {}
485
486private:
487 std::mutex mCallbackMutex; // Protects the following
488 sp<VSyncSource::Callback> mCallback;
489};
490
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700492 ALOGI( "SurfaceFlinger's main thread ready to run. "
493 "Initializing graphics H/W...");
494
Dan Stoza9e56aa02015-11-02 13:00:03 -0800495 { // Autolock scope
496 Mutex::Autolock _l(mStateLock);
497
498 // initialize EGL for the default display
499 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
500 eglInitialize(mEGLDisplay, NULL, NULL);
501
502 // start the EventThread
503 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
504 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000505 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800506 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
507 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000508 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800509 mEventQueue.setEventThread(mSFEventThread);
510
Tim Murrayacff43d2016-07-29 13:57:24 -0700511 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700512 struct sched_param param = {0};
513 param.sched_priority = 1;
Tim Murray41a38532016-06-22 12:42:10 -0700514 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
515 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
516 }
517
Dan Stoza9e56aa02015-11-02 13:00:03 -0800518 // Get a RenderEngine for the given display / config (can't fail)
519 mRenderEngine = RenderEngine::create(mEGLDisplay,
520 HAL_PIXEL_FORMAT_RGBA_8888);
521 }
522
523 // Drop the state lock while we initialize the hardware composer. We drop
524 // the lock because on creation, it will call back into SurfaceFlinger to
525 // initialize the primary display.
526 mHwc = new HWComposer(this);
527 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
528
Jesse Hall692c7232012-11-08 15:41:56 -0800529 Mutex::Autolock _l(mStateLock);
530
Mathias Agopian875d8e12013-06-07 15:35:48 -0700531 // retrieve the EGL context that was selected/created
532 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700533
Mathias Agopianda27af92012-09-13 18:17:13 -0700534 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
535 "couldn't create EGLContext");
536
Dan Stoza9e56aa02015-11-02 13:00:03 -0800537 // make the GLContext current so that we can create textures when creating
538 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700539 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
540
Jamie Gennisd1700752013-10-14 12:22:52 -0700541 mEventControlThread = new EventControlThread(this);
542 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
543
Mathias Agopian92a979a2012-08-02 18:32:23 -0700544 // initialize our drawing state
545 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700546
Andy McFadden13a082e2012-08-24 10:16:42 -0700547 // set initial conditions (e.g. unblank default device)
548 initializeDisplays();
549
Dan Stoza4e637772016-07-28 13:31:51 -0700550 mRenderEngine->primeCache();
551
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700552 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700553 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554
Dan Stoza9e56aa02015-11-02 13:00:03 -0800555 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700556}
557
Mathias Agopiana67e4182012-06-19 17:26:12 -0700558void SurfaceFlinger::startBootAnim() {
559 // start boot animation
560 property_set("service.bootanim.exit", "0");
561 property_set("ctl.start", "bootanim");
562}
563
Mathias Agopian875d8e12013-06-07 15:35:48 -0700564size_t SurfaceFlinger::getMaxTextureSize() const {
565 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700566}
567
Mathias Agopian875d8e12013-06-07 15:35:48 -0700568size_t SurfaceFlinger::getMaxViewportDims() const {
569 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700570}
571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800573
Jamie Gennis582270d2011-08-17 18:19:00 -0700574bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800575 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800576 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800577 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700578 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800579}
580
Dan Stoza7f7da322014-05-02 15:26:25 -0700581status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
582 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700583 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700584 return BAD_VALUE;
585 }
586
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500587 if (!display.get())
588 return NAME_NOT_FOUND;
589
Jesse Hall692c7232012-11-08 15:41:56 -0800590 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700591 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800592 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700593 type = i;
594 break;
595 }
596 }
597
598 if (type < 0) {
599 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700600 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700601
Mathias Agopian8b736f12012-08-13 17:54:26 -0700602 // TODO: Not sure if display density should handled by SF any longer
603 class Density {
604 static int getDensityFromProperty(char const* propName) {
605 char property[PROPERTY_VALUE_MAX];
606 int density = 0;
607 if (property_get(propName, property, NULL) > 0) {
608 density = atoi(property);
609 }
610 return density;
611 }
612 public:
613 static int getEmuDensity() {
614 return getDensityFromProperty("qemu.sf.lcd_density"); }
615 static int getBuildDensity() {
616 return getDensityFromProperty("ro.sf.lcd_density"); }
617 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700618
Dan Stoza7f7da322014-05-02 15:26:25 -0700619 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700620
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700622 DisplayInfo info = DisplayInfo();
623
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624 float xdpi = hwConfig->getDpiX();
625 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700626
627 if (type == DisplayDevice::DISPLAY_PRIMARY) {
628 // The density of the device is provided by a build property
629 float density = Density::getBuildDensity() / 160.0f;
630 if (density == 0) {
631 // the build doesn't provide a density -- this is wrong!
632 // use xdpi instead
633 ALOGE("ro.sf.lcd_density must be defined as a build property");
634 density = xdpi / 160.0f;
635 }
636 if (Density::getEmuDensity()) {
637 // if "qemu.sf.lcd_density" is specified, it overrides everything
638 xdpi = ydpi = density = Density::getEmuDensity();
639 density /= 160.0f;
640 }
641 info.density = density;
642
643 // TODO: this needs to go away (currently needed only by webkit)
644 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
645 info.orientation = hw->getOrientation();
646 } else {
647 // TODO: where should this value come from?
648 static const int TV_DENSITY = 213;
649 info.density = TV_DENSITY / 160.0f;
650 info.orientation = 0;
651 }
652
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653 info.w = hwConfig->getWidth();
654 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700655 info.xdpi = xdpi;
656 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800657 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700658 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659
Andy McFadden91b2ca82014-06-13 14:04:23 -0700660 // This is how far in advance a buffer must be queued for
661 // presentation at a given time. If you want a buffer to appear
662 // on the screen at time N, you must submit the buffer before
663 // (N - presentationDeadline).
664 //
665 // Normally it's one full refresh period (to give SF a chance to
666 // latch the buffer), but this can be reduced by configuring a
667 // DispSync offset. Any additional delays introduced by the hardware
668 // composer or panel must be accounted for here.
669 //
670 // We add an additional 1ms to allow for processing time and
671 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672 info.presentationDeadline = hwConfig->getVsyncPeriod() -
673 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700674
675 // All non-virtual displays are currently considered secure.
676 info.secure = true;
677
Michael Wright28f24d02016-07-12 13:30:53 -0700678 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700679 }
680
Dan Stoza7f7da322014-05-02 15:26:25 -0700681 return NO_ERROR;
682}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700683
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800684status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700685 DisplayStatInfo* stats) {
686 if (stats == NULL) {
687 return BAD_VALUE;
688 }
689
690 // FIXME for now we always return stats for the primary display
691 memset(stats, 0, sizeof(*stats));
692 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
693 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
694 return NO_ERROR;
695}
696
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700697int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700698 sp<DisplayDevice> device(getDisplayDevice(display));
699 if (device != NULL) {
700 return device->getActiveConfig();
701 }
702 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700703}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700704
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700705void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
706 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
707 this);
708 int32_t type = hw->getDisplayType();
709 int currentMode = hw->getActiveConfig();
710
711 if (mode == currentMode) {
712 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
713 return;
714 }
715
716 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
717 ALOGW("Trying to set config for virtual display");
718 return;
719 }
720
721 hw->setActiveConfig(mode);
722 getHwComposer().setActiveConfig(type, mode);
723}
724
725status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
726 class MessageSetActiveConfig: public MessageBase {
727 SurfaceFlinger& mFlinger;
728 sp<IBinder> mDisplay;
729 int mMode;
730 public:
731 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
732 int mode) :
733 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
734 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700735 Vector<DisplayInfo> configs;
736 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700737 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700738 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700739 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700740 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700741 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700742 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
743 if (hw == NULL) {
744 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700745 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700746 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
747 ALOGW("Attempt to set active config = %d for virtual display",
748 mMode);
749 } else {
750 mFlinger.setActiveConfigInternal(hw, mMode);
751 }
752 return true;
753 }
754 };
755 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
756 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700757 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700758}
Michael Wright28f24d02016-07-12 13:30:53 -0700759status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
760 Vector<android_color_mode_t>* outColorModes) {
761 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
762 return BAD_VALUE;
763 }
764
765 if (!display.get()) {
766 return NAME_NOT_FOUND;
767 }
768
769 int32_t type = NAME_NOT_FOUND;
770 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
771 if (display == mBuiltinDisplays[i]) {
772 type = i;
773 break;
774 }
775 }
776
777 if (type < 0) {
778 return type;
779 }
780
781 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
782 outColorModes->clear();
783 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
784
785 return NO_ERROR;
786}
787
788android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
789 sp<DisplayDevice> device(getDisplayDevice(display));
790 if (device != nullptr) {
791 return device->getActiveColorMode();
792 }
793 return static_cast<android_color_mode_t>(BAD_VALUE);
794}
795
796void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
797 android_color_mode_t mode) {
798 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
799 this);
800 int32_t type = hw->getDisplayType();
801 android_color_mode_t currentMode = hw->getActiveColorMode();
802
803 if (mode == currentMode) {
804 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
805 return;
806 }
807
808 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
809 ALOGW("Trying to set config for virtual display");
810 return;
811 }
812
813 hw->setActiveColorMode(mode);
814 getHwComposer().setActiveColorMode(type, mode);
815}
816
817
818status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
819 android_color_mode_t colorMode) {
820 class MessageSetActiveColorMode: public MessageBase {
821 SurfaceFlinger& mFlinger;
822 sp<IBinder> mDisplay;
823 android_color_mode_t mMode;
824 public:
825 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
826 android_color_mode_t mode) :
827 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
828 virtual bool handler() {
829 Vector<android_color_mode_t> modes;
830 mFlinger.getDisplayColorModes(mDisplay, &modes);
831 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
832 if (mMode < 0 || !exists) {
833 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
834 mDisplay.get());
835 return true;
836 }
837 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
838 if (hw == nullptr) {
839 ALOGE("Attempt to set active color mode = %d for null display %p",
840 mMode, mDisplay.get());
841 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
842 ALOGW("Attempt to set active color mode= %d for virtual display",
843 mMode);
844 } else {
845 mFlinger.setActiveColorModeInternal(hw, mMode);
846 }
847 return true;
848 }
849 };
850 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
851 postMessageSync(msg);
852 return NO_ERROR;
853}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700854
Svetoslavd85084b2014-03-20 10:28:31 -0700855status_t SurfaceFlinger::clearAnimationFrameStats() {
856 Mutex::Autolock _l(mStateLock);
857 mAnimFrameTracker.clearStats();
858 return NO_ERROR;
859}
860
861status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
862 Mutex::Autolock _l(mStateLock);
863 mAnimFrameTracker.getStats(outStats);
864 return NO_ERROR;
865}
866
Dan Stozac4f471e2016-03-24 09:31:08 -0700867status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
868 HdrCapabilities* outCapabilities) const {
869 Mutex::Autolock _l(mStateLock);
870
871 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
872 if (displayDevice == nullptr) {
873 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
874 return BAD_VALUE;
875 }
876
877 std::unique_ptr<HdrCapabilities> capabilities =
878 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
879 if (capabilities) {
880 std::swap(*outCapabilities, *capabilities);
881 } else {
882 return BAD_VALUE;
883 }
884
885 return NO_ERROR;
886}
887
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700888status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
889 if (enable == mInjectVSyncs) {
890 return NO_ERROR;
891 }
892
893 if (enable) {
894 mInjectVSyncs = enable;
895 ALOGV("VSync Injections enabled");
896 if (mVSyncInjector.get() == nullptr) {
897 mVSyncInjector = new InjectVSyncSource();
898 mInjectorEventThread = new EventThread(mVSyncInjector, *this);
899 }
900 mEventQueue.setEventThread(mInjectorEventThread);
901 } else {
902 mInjectVSyncs = enable;
903 ALOGV("VSync Injections disabled");
904 mEventQueue.setEventThread(mSFEventThread);
905 mVSyncInjector.clear();
906 }
907 return NO_ERROR;
908}
909
910status_t SurfaceFlinger::injectVSync(nsecs_t when) {
911 if (!mInjectVSyncs) {
912 ALOGE("VSync Injections not enabled");
913 return BAD_VALUE;
914 }
915 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
916 ALOGV("Injecting VSync inside SurfaceFlinger");
917 mVSyncInjector->onInjectSyncEvent(when);
918 }
919 return NO_ERROR;
920}
921
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800922// ----------------------------------------------------------------------------
923
924sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800925 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700926}
927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800928// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800929
930void SurfaceFlinger::waitForEvent() {
931 mEventQueue.waitMessage();
932}
933
934void SurfaceFlinger::signalTransaction() {
935 mEventQueue.invalidate();
936}
937
938void SurfaceFlinger::signalLayerUpdate() {
939 mEventQueue.invalidate();
940}
941
942void SurfaceFlinger::signalRefresh() {
943 mEventQueue.refresh();
944}
945
946status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800947 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800948 return mEventQueue.postMessage(msg, reltime);
949}
950
951status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800952 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800953 status_t res = mEventQueue.postMessage(msg, reltime);
954 if (res == NO_ERROR) {
955 msg->wait();
956 }
957 return res;
958}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800959
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700960void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700961 do {
962 waitForEvent();
963 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800964}
965
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700966void SurfaceFlinger::enableHardwareVsync() {
967 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700968 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700969 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700970 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
971 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700972 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700973 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700974}
975
Jesse Hall948fe0c2013-10-14 12:56:09 -0700976void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700977 Mutex::Autolock _l(mHWVsyncLock);
978
Jesse Hall948fe0c2013-10-14 12:56:09 -0700979 if (makeAvailable) {
980 mHWVsyncAvailable = true;
981 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700982 // Hardware vsync is not currently available, so abort the resync
983 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700984 return;
985 }
986
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
988 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700989
990 mPrimaryDispSync.reset();
991 mPrimaryDispSync.setPeriod(period);
992
993 if (!mPrimaryHWVsyncEnabled) {
994 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700995 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
996 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700997 mPrimaryHWVsyncEnabled = true;
998 }
999}
1000
Jesse Hall948fe0c2013-10-14 12:56:09 -07001001void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001002 Mutex::Autolock _l(mHWVsyncLock);
1003 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001004 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1005 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001006 mPrimaryDispSync.endResync();
1007 mPrimaryHWVsyncEnabled = false;
1008 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001009 if (makeUnavailable) {
1010 mHWVsyncAvailable = false;
1011 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001012}
1013
Tim Murray4a4e4a22016-04-19 16:29:23 +00001014void SurfaceFlinger::resyncWithRateLimit() {
1015 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1016 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001017 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001018 }
1019}
1020
Dan Stoza9e56aa02015-11-02 13:00:03 -08001021void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001022 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001023
Jamie Gennisd1700752013-10-14 12:22:52 -07001024 { // Scope for the lock
1025 Mutex::Autolock _l(mHWVsyncLock);
1026 if (type == 0 && mPrimaryHWVsyncEnabled) {
1027 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001028 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001029 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001030
1031 if (needsHwVsync) {
1032 enableHardwareVsync();
1033 } else {
1034 disableHardwareVsync(false);
1035 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001036}
1037
Dan Stoza9e56aa02015-11-02 13:00:03 -08001038void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1039 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1040 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1041 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001042
Dan Stoza9e56aa02015-11-02 13:00:03 -08001043 // All non-virtual displays are currently considered secure.
1044 bool isSecure = true;
1045
1046 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1047 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1048 wp<IBinder> token = mBuiltinDisplays[type];
1049
1050 sp<IGraphicBufferProducer> producer;
1051 sp<IGraphicBufferConsumer> consumer;
1052 BufferQueue::createBufferQueue(&producer, &consumer,
1053 new GraphicBufferAlloc());
1054
1055 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1056 DisplayDevice::DISPLAY_PRIMARY, consumer);
1057 sp<DisplayDevice> hw = new DisplayDevice(this,
1058 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1059 producer, mRenderEngine->getEGLConfig());
1060 mDisplays.add(token, hw);
1061 } else {
1062 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001063 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001064 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001065 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001066 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001067 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1068 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001069 }
1070 setTransactionFlags(eDisplayTransactionNeeded);
1071
Andy McFadden9e9689c2012-10-10 18:17:51 -07001072 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001073 }
Mathias Agopian86303202012-07-24 22:46:10 -07001074}
1075
Dan Stoza9e56aa02015-11-02 13:00:03 -08001076void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001078 getHwComposer().setVsyncEnabled(disp,
1079 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001080}
1081
Mathias Agopian4fec8732012-06-29 14:12:52 -07001082void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001083 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001084 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001085 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001086 bool frameMissed = !mHadClientComposition &&
1087 mPreviousPresentFence != Fence::NO_FENCE &&
1088 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1089 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001090 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001091 signalLayerUpdate();
1092 break;
1093 }
1094
Dan Stoza6b9454d2014-11-07 16:00:59 -08001095 bool refreshNeeded = handleMessageTransaction();
1096 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001097 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001098 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001099 // Signal a refresh if a transaction modified the window state,
1100 // a new buffer was latched, or if HWC has requested a full
1101 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001102 signalRefresh();
1103 }
1104 break;
1105 }
1106 case MessageQueue::REFRESH: {
1107 handleMessageRefresh();
1108 break;
1109 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001110 }
1111}
1112
Dan Stoza6b9454d2014-11-07 16:00:59 -08001113bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001114 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001115 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001116 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001117 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001118 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001119 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001120}
1121
Dan Stoza6b9454d2014-11-07 16:00:59 -08001122bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001123 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001124 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001125}
1126
1127void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001128 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001129
Pablo Ceballos40845df2016-01-25 17:41:15 -08001130 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001131
Dan Stoza05dacfb2016-07-01 13:33:38 -07001132 preComposition();
1133 rebuildLayerStacks();
1134 setUpHWComposer();
1135 doDebugFlashRegions();
1136 doComposition();
1137 postComposition(refreshStartTime);
1138
1139 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001140
1141 mHadClientComposition = false;
1142 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1143 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1144 mHadClientComposition = mHadClientComposition ||
1145 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1146 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001147
Dan Stoza9e56aa02015-11-02 13:00:03 -08001148 // Release any buffers which were replaced this frame
1149 for (auto& layer : mLayersWithQueuedFrames) {
1150 layer->releasePendingBuffer();
1151 }
1152 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001153}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001154
Mathias Agopiancd60f992012-08-16 16:28:27 -07001155void SurfaceFlinger::doDebugFlashRegions()
1156{
1157 // is debugging enabled
1158 if (CC_LIKELY(!mDebugRegion))
1159 return;
1160
1161 const bool repaintEverything = mRepaintEverything;
1162 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1163 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001164 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001165 // transform the dirty region into this screen's coordinate space
1166 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1167 if (!dirtyRegion.isEmpty()) {
1168 // redraw the whole screen
1169 doComposeSurfaces(hw, Region(hw->bounds()));
1170
1171 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001172 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001173 RenderEngine& engine(getRenderEngine());
1174 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1175
Mathias Agopianda27af92012-09-13 18:17:13 -07001176 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001177 }
1178 }
1179 }
1180
1181 postFramebuffer();
1182
1183 if (mDebugRegion > 1) {
1184 usleep(mDebugRegion * 1000);
1185 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001186
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001188 auto& displayDevice = mDisplays[displayId];
1189 if (!displayDevice->isDisplayOn()) {
1190 continue;
1191 }
1192
1193 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1195 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001196 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001197}
1198
1199void SurfaceFlinger::preComposition()
1200{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001201 ATRACE_CALL();
1202 ALOGV("preComposition");
1203
Mathias Agopiancd60f992012-08-16 16:28:27 -07001204 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001205 const LayerVector& layers(mDrawingState.layersSortedByZ);
1206 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001207 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001208 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001209 needExtraInvalidate = true;
1210 }
1211 }
1212 if (needExtraInvalidate) {
1213 signalLayerUpdate();
1214 }
1215}
1216
Pablo Ceballos40845df2016-01-25 17:41:15 -08001217void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001218{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 ATRACE_CALL();
1220 ALOGV("postComposition");
1221
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001222 const LayerVector& layers(mDrawingState.layersSortedByZ);
1223 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001224 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001225 bool frameLatched = layers[i]->onPostComposition();
1226 if (frameLatched) {
1227 recordBufferingStats(layers[i]->getName().string(),
1228 layers[i]->getOccupancyHistory(false));
1229 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001230 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001231
Dan Stoza9e56aa02015-11-02 13:00:03 -08001232 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233
1234 if (presentFence->isValid()) {
1235 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1236 enableHardwareVsync();
1237 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001239 }
1240 }
1241
Dan Stozab90cf072015-03-05 11:05:59 -08001242 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001243 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001244 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245 enableHardwareVsync();
1246 }
1247 }
1248
Pablo Ceballos40845df2016-01-25 17:41:15 -08001249 mFenceTracker.addFrame(refreshStartTime, presentFence,
1250 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1251
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001252 if (mAnimCompositionPending) {
1253 mAnimCompositionPending = false;
1254
Jesse Halla9a1b002013-02-27 16:39:25 -08001255 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001256 mAnimFrameTracker.setActualPresentFence(presentFence);
1257 } else {
1258 // The HWC doesn't support present fences, so use the refresh
1259 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260 nsecs_t presentTime =
1261 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001262 mAnimFrameTracker.setActualPresentTime(presentTime);
1263 }
1264 mAnimFrameTracker.advanceFrame();
1265 }
Dan Stozab90cf072015-03-05 11:05:59 -08001266
1267 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1268 return;
1269 }
1270
1271 nsecs_t currentTime = systemTime();
1272 if (mHasPoweredOff) {
1273 mHasPoweredOff = false;
1274 } else {
1275 nsecs_t period = mPrimaryDispSync.getPeriod();
1276 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1277 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1278 if (numPeriods < NUM_BUCKETS - 1) {
1279 mFrameBuckets[numPeriods] += elapsedTime;
1280 } else {
1281 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1282 }
1283 mTotalTime += elapsedTime;
1284 }
1285 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001286}
1287
1288void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001289 ATRACE_CALL();
1290 ALOGV("rebuildLayerStacks");
1291
Mathias Agopiancd60f992012-08-16 16:28:27 -07001292 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001293 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001294 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001295 mVisibleRegionsDirty = false;
1296 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001297
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001298 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001299 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001300 Region opaqueRegion;
1301 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 Vector<sp<Layer>> layersSortedByZ;
1303 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1304 const Transform& tr(displayDevice->getTransform());
1305 const Rect bounds(displayDevice->getBounds());
1306 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001307 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 displayDevice->getLayerStack(), dirtyRegion,
1309 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001310
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001311 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001312 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001313 const sp<Layer>& layer(layers[i]);
1314 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001316 Region drawRegion(tr.transform(
1317 layer->visibleNonTransparentRegion));
1318 drawRegion.andSelf(bounds);
1319 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001320 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 } else {
1322 // Clear out the HWC layer if this layer was
1323 // previously visible, but no longer is
1324 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1325 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001326 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001327 }
1328 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001329 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1331 displayDevice->undefinedRegion.set(bounds);
1332 displayDevice->undefinedRegion.subtractSelf(
1333 tr.transform(opaqueRegion));
1334 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001335 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001336 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001337}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001338
Mathias Agopiancd60f992012-08-16 16:28:27 -07001339void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001340 ATRACE_CALL();
1341 ALOGV("setUpHWComposer");
1342
Jesse Hall028dc8f2013-08-20 16:35:32 -07001343 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001344 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1345 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1346 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1347
1348 // If nothing has changed (!dirty), don't recompose.
1349 // If something changed, but we don't currently have any visible layers,
1350 // and didn't when we last did a composition, then skip it this time.
1351 // The second rule does two things:
1352 // - When all layers are removed from a display, we'll emit one black
1353 // frame, then nothing more until we get new layers.
1354 // - When a display is created with a private layer stack, we won't
1355 // emit any black frames until a layer is added to the layer stack.
1356 bool mustRecompose = dirty && !(empty && wasEmpty);
1357
1358 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1359 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1360 mustRecompose ? "doing" : "skipping",
1361 dirty ? "+" : "-",
1362 empty ? "+" : "-",
1363 wasEmpty ? "+" : "-");
1364
Dan Stoza71433162014-02-04 16:22:36 -08001365 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001366
1367 if (mustRecompose) {
1368 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1369 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001370 }
1371
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 // build the h/w work list
1373 if (CC_UNLIKELY(mGeometryInvalid)) {
1374 mGeometryInvalid = false;
1375 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1376 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1377 const auto hwcId = displayDevice->getHwcDisplayId();
1378 if (hwcId >= 0) {
1379 const Vector<sp<Layer>>& currentLayers(
1380 displayDevice->getVisibleLayersSortedByZ());
1381 bool foundLayerWithoutHwc = false;
1382 for (auto& layer : currentLayers) {
1383 if (!layer->hasHwcLayer(hwcId)) {
1384 auto hwcLayer = mHwc->createLayer(hwcId);
1385 if (hwcLayer) {
1386 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1387 } else {
1388 layer->forceClientComposition(hwcId);
1389 foundLayerWithoutHwc = true;
1390 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001391 }
1392 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001395 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001397 }
1398 }
1399 }
1400 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001401 }
Riley Andrews03414a12014-07-01 14:22:59 -07001402
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001403
1404 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1405
Dan Stoza9e56aa02015-11-02 13:00:03 -08001406 // Set the per-frame data
1407 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1408 auto& displayDevice = mDisplays[displayId];
1409 const auto hwcId = displayDevice->getHwcDisplayId();
1410 if (hwcId < 0) {
1411 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001412 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001413 if (colorMatrix != mPreviousColorMatrix) {
1414 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1415 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1416 "display %zd: %d", displayId, result);
1417 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001418 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1419 layer->setPerFrameData(displayDevice);
1420 }
1421 }
1422
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001423 mPreviousColorMatrix = colorMatrix;
1424
Dan Stoza9e56aa02015-11-02 13:00:03 -08001425 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001426 auto& displayDevice = mDisplays[displayId];
1427 if (!displayDevice->isDisplayOn()) {
1428 continue;
1429 }
1430
1431 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001432 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1433 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001434 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001435}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001436
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437void SurfaceFlinger::doComposition() {
1438 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001439 ALOGV("doComposition");
1440
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001441 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001442 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001443 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001444 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445 // transform the dirty region into this screen's coordinate space
1446 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001447
1448 // repaint the framebuffer (if needed)
1449 doDisplayComposition(hw, dirtyRegion);
1450
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451 hw->dirtyRegion.clear();
1452 hw->flip(hw->swapRegion);
1453 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001454 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001456 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001457}
1458
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001459void SurfaceFlinger::postFramebuffer()
1460{
Mathias Agopian841cde52012-03-01 15:44:37 -08001461 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001462 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001463
Mathias Agopiana44b0412011-10-16 18:46:35 -07001464 const nsecs_t now = systemTime();
1465 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001466
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1468 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001469 if (!displayDevice->isDisplayOn()) {
1470 continue;
1471 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001472 const auto hwcId = displayDevice->getHwcDisplayId();
1473 if (hwcId >= 0) {
1474 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001475 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001476 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 if (displayId == 0) {
1478 // Make the default display current because the VirtualDisplayDevice
1479 // code cannot deal with dequeueBuffer() being called outside of the
1480 // composition loop; however the code below can call glFlush() which
1481 // is allowed to (and does in some case) call dequeueBuffer().
1482 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1483 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1485 sp<Fence> releaseFence = Fence::NO_FENCE;
1486 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1487 releaseFence = displayDevice->getClientTargetAcquireFence();
1488 } else {
1489 auto hwcLayer = layer->getHwcLayer(hwcId);
1490 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001491 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 layer->onLayerDisplayed(releaseFence);
1493 }
1494 if (hwcId >= 0) {
1495 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001496 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001497 }
1498
Mathias Agopiana44b0412011-10-16 18:46:35 -07001499 mLastSwapBufferTime = systemTime() - now;
1500 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001501
1502 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1503 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1504 logFrameStats();
1505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506}
1507
Mathias Agopian87baae12012-07-31 12:38:26 -07001508void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509{
Mathias Agopian841cde52012-03-01 15:44:37 -08001510 ATRACE_CALL();
1511
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001512 // here we keep a copy of the drawing state (that is the state that's
1513 // going to be overwritten by handleTransactionLocked()) outside of
1514 // mStateLock so that the side-effects of the State assignment
1515 // don't happen with mStateLock held (which can cause deadlocks).
1516 State drawingState(mDrawingState);
1517
Mathias Agopianca4d3602011-05-19 15:38:14 -07001518 Mutex::Autolock _l(mStateLock);
1519 const nsecs_t now = systemTime();
1520 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521
Mathias Agopianca4d3602011-05-19 15:38:14 -07001522 // Here we're guaranteed that some transaction flags are set
1523 // so we can call handleTransactionLocked() unconditionally.
1524 // We call getTransactionFlags(), which will also clear the flags,
1525 // with mStateLock held to guarantee that mCurrentState won't change
1526 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001527
Mathias Agopiane57f2922012-08-09 16:29:12 -07001528 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001529 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001530
Mathias Agopianca4d3602011-05-19 15:38:14 -07001531 mLastTransactionTime = systemTime() - now;
1532 mDebugInTransaction = 0;
1533 invalidateHwcGeometry();
1534 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001535}
1536
Mathias Agopian87baae12012-07-31 12:38:26 -07001537void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001538{
1539 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001540 const size_t count = currentLayers.size();
1541
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 // Notify all layers of available frames
1543 for (size_t i = 0; i < count; ++i) {
1544 currentLayers[i]->notifyAvailableFrames();
1545 }
1546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547 /*
1548 * Traversal of the children
1549 * (perform the transaction for each of them if needed)
1550 */
1551
Mathias Agopian3559b072012-08-15 13:46:03 -07001552 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001554 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001555 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1556 if (!trFlags) continue;
1557
1558 const uint32_t flags = layer->doTransaction(0);
1559 if (flags & Layer::eVisibleRegion)
1560 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001561 }
1562 }
1563
1564 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001565 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001566 */
1567
Mathias Agopiane57f2922012-08-09 16:29:12 -07001568 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001569 // here we take advantage of Vector's copy-on-write semantics to
1570 // improve performance by skipping the transaction entirely when
1571 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001572 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1573 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001574 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001575 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001576 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001577 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001578
1579 // find the displays that were removed
1580 // (ie: in drawing state but not in current state)
1581 // also handle displays that changed
1582 // (ie: displays that are in both lists)
1583 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001584 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1585 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001586 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001587 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001588 // Call makeCurrent() on the primary display so we can
1589 // be sure that nothing associated with this display
1590 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001591 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001592 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001593 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1594 if (hw != NULL)
1595 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001596 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001597 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001598 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001599 } else {
1600 ALOGW("trying to remove the main display");
1601 }
1602 } else {
1603 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001604 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001605 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001606 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1607 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001608 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001609 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001610 // recreating the DisplayDevice, so we just remove it
1611 // from the drawing state, so that it get re-added
1612 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001613 sp<DisplayDevice> hw(getDisplayDevice(display));
1614 if (hw != NULL)
1615 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001616 mDisplays.removeItem(display);
1617 mDrawingState.displays.removeItemsAt(i);
1618 dc--; i--;
1619 // at this point we must loop to the next item
1620 continue;
1621 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001622
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001623 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001624 if (disp != NULL) {
1625 if (state.layerStack != draw[i].layerStack) {
1626 disp->setLayerStack(state.layerStack);
1627 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001628 if ((state.orientation != draw[i].orientation)
1629 || (state.viewport != draw[i].viewport)
1630 || (state.frame != draw[i].frame))
1631 {
1632 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001633 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001634 }
Michael Lentine47e45402014-07-18 15:34:25 -07001635 if (state.width != draw[i].width || state.height != draw[i].height) {
1636 disp->setDisplaySize(state.width, state.height);
1637 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001638 }
1639 }
1640 }
1641
1642 // find displays that were added
1643 // (ie: in current state but not in drawing state)
1644 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001645 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001646 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001647
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001648 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001649 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001650 sp<IGraphicBufferProducer> bqProducer;
1651 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001652 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1653 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001654
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001656 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001657 // Virtual displays without a surface are dormant:
1658 // they have external state (layer stack, projection,
1659 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001660 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001661
Dan Stoza8cf150a2016-08-02 10:27:31 -07001662 if (mUseHwcVirtualDisplays) {
1663 int width = 0;
1664 int status = state.surface->query(
1665 NATIVE_WINDOW_WIDTH, &width);
1666 ALOGE_IF(status != NO_ERROR,
1667 "Unable to query width (%d)", status);
1668 int height = 0;
1669 status = state.surface->query(
1670 NATIVE_WINDOW_HEIGHT, &height);
1671 ALOGE_IF(status != NO_ERROR,
1672 "Unable to query height (%d)", status);
1673 int intFormat = 0;
1674 status = state.surface->query(
1675 NATIVE_WINDOW_FORMAT, &intFormat);
1676 ALOGE_IF(status != NO_ERROR,
1677 "Unable to query format (%d)", status);
1678 auto format = static_cast<android_pixel_format_t>(
1679 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001680
Dan Stoza8cf150a2016-08-02 10:27:31 -07001681 mHwc->allocateVirtualDisplay(width, height, &format,
1682 &hwcId);
1683 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684
Dan Stoza5cf424b2016-05-20 14:02:39 -07001685 // TODO: Plumb requested format back up to consumer
1686
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 sp<VirtualDisplaySurface> vds =
1688 new VirtualDisplaySurface(*mHwc,
1689 hwcId, state.surface, bqProducer,
1690 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001691
1692 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001693 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001694 }
1695 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001696 ALOGE_IF(state.surface!=NULL,
1697 "adding a supported display, but rendering "
1698 "surface is provided (%p), ignoring it",
1699 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1701 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1702 dispSurface = new FramebufferSurface(*mHwc,
1703 DisplayDevice::DISPLAY_EXTERNAL,
1704 bqConsumer);
1705 producer = bqProducer;
1706 } else {
1707 ALOGE("Attempted to add non-external non-virtual"
1708 " display");
1709 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001710 }
1711
1712 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001713 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001714 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 state.type, hwcId, state.isSecure, display,
1716 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001717 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001718 hw->setLayerStack(state.layerStack);
1719 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001720 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001721 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001722 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001724 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001725 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001726 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001727 }
1728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001729 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001731
Mathias Agopian84300952012-11-21 16:02:13 -08001732 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1733 // The transform hint might have changed for some layers
1734 // (either because a display has changed, or because a layer
1735 // as changed).
1736 //
1737 // Walk through all the layers in currentLayers,
1738 // and update their transform hint.
1739 //
1740 // If a layer is visible only on a single display, then that
1741 // display is used to calculate the hint, otherwise we use the
1742 // default display.
1743 //
1744 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1745 // the hint is set before we acquire a buffer from the surface texture.
1746 //
1747 // NOTE: layer transactions have taken place already, so we use their
1748 // drawing state. However, SurfaceFlinger's own transaction has not
1749 // happened yet, so we must use the current state layer list
1750 // (soon to become the drawing state list).
1751 //
1752 sp<const DisplayDevice> disp;
1753 uint32_t currentlayerStack = 0;
1754 for (size_t i=0; i<count; i++) {
1755 // NOTE: we rely on the fact that layers are sorted by
1756 // layerStack first (so we don't have to traverse the list
1757 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001758 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001759 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001760 if (i==0 || currentlayerStack != layerStack) {
1761 currentlayerStack = layerStack;
1762 // figure out if this layerstack is mirrored
1763 // (more than one display) if so, pick the default display,
1764 // if not, pick the only display it's on.
1765 disp.clear();
1766 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1767 sp<const DisplayDevice> hw(mDisplays[dpy]);
1768 if (hw->getLayerStack() == currentlayerStack) {
1769 if (disp == NULL) {
1770 disp = hw;
1771 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001772 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001773 break;
1774 }
1775 }
1776 }
1777 }
Chet Haase91d25932013-04-11 15:24:55 -07001778 if (disp == NULL) {
1779 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1780 // redraw after transform hint changes. See bug 8508397.
1781
1782 // could be null when this layer is using a layerStack
1783 // that is not visible on any display. Also can occur at
1784 // screen off/on times.
1785 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001786 }
Chet Haase91d25932013-04-11 15:24:55 -07001787 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001788 }
1789 }
1790
1791
Mathias Agopian3559b072012-08-15 13:46:03 -07001792 /*
1793 * Perform our own transaction if needed
1794 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001795
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001796 const LayerVector& layers(mDrawingState.layersSortedByZ);
1797 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001798 // layers have been added
1799 mVisibleRegionsDirty = true;
1800 }
1801
1802 // some layers might have been removed, so
1803 // we need to update the regions they're exposing.
1804 if (mLayersRemoved) {
1805 mLayersRemoved = false;
1806 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001807 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001808 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001809 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001810 if (currentLayers.indexOf(layer) < 0) {
1811 // this layer is not visible anymore
1812 // TODO: we could traverse the tree from front to back and
1813 // compute the actual visible region
1814 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001815 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001816 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001817 Region(Rect(s.active.w, s.active.h)));
1818 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 }
1822
1823 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001824
1825 updateCursorAsync();
1826}
1827
1828void SurfaceFlinger::updateCursorAsync()
1829{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1831 auto& displayDevice = mDisplays[displayId];
1832 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001833 continue;
1834 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001835
1836 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1837 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001838 }
1839 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001840}
1841
1842void SurfaceFlinger::commitTransaction()
1843{
1844 if (!mLayersPendingRemoval.isEmpty()) {
1845 // Notify removed layers now that they can't be drawn from
1846 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001847 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1848 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001849 mLayersPendingRemoval[i]->onRemoved();
1850 }
1851 mLayersPendingRemoval.clear();
1852 }
1853
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001854 // If this transaction is part of a window animation then the next frame
1855 // we composite should be considered an animation as well.
1856 mAnimCompositionPending = mAnimTransactionPending;
1857
Mathias Agopian4fec8732012-06-29 14:12:52 -07001858 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001859 mTransactionPending = false;
1860 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001861 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862}
1863
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001864void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001865 const LayerVector& currentLayers, uint32_t layerStack,
1866 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001867{
Mathias Agopian841cde52012-03-01 15:44:37 -08001868 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001870
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001871 Region aboveOpaqueLayers;
1872 Region aboveCoveredLayers;
1873 Region dirty;
1874
Mathias Agopian87baae12012-07-31 12:38:26 -07001875 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001876
1877 size_t i = currentLayers.size();
1878 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001879 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001880
1881 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001882 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001883
Jesse Hall01e29052013-02-19 16:13:35 -08001884 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001885 if (s.layerStack != layerStack)
1886 continue;
1887
Mathias Agopianab028732010-03-16 16:41:46 -07001888 /*
1889 * opaqueRegion: area of a surface that is fully opaque.
1890 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001892
1893 /*
1894 * visibleRegion: area of a surface that is visible on screen
1895 * and not fully transparent. This is essentially the layer's
1896 * footprint minus the opaque regions above it.
1897 * Areas covered by a translucent surface are considered visible.
1898 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001900
1901 /*
1902 * coveredRegion: area of a surface that is covered by all
1903 * visible regions above it (which includes the translucent areas).
1904 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001905 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001906
Jesse Halla8026d22012-09-25 13:25:04 -07001907 /*
1908 * transparentRegion: area of a surface that is hinted to be completely
1909 * transparent. This is only used to tell when the layer has no visible
1910 * non-transparent regions and can be removed from the layer list. It
1911 * does not affect the visibleRegion of this layer or any layers
1912 * beneath it. The hint may not be correct if apps don't respect the
1913 * SurfaceView restrictions (which, sadly, some don't).
1914 */
1915 Region transparentRegion;
1916
Mathias Agopianab028732010-03-16 16:41:46 -07001917
1918 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001919 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001920 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001921 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001922 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001923 if (!visibleRegion.isEmpty()) {
1924 // Remove the transparent area from the visible region
1925 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001926 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001927 if (tr.preserveRects()) {
1928 // transform the transparent region
1929 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001930 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001931 // transformation too complex, can't do the
1932 // transparent region optimization.
1933 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001934 }
Mathias Agopianab028732010-03-16 16:41:46 -07001935 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001936
Mathias Agopianab028732010-03-16 16:41:46 -07001937 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001938 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001940 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1941 // the opaque region is the layer's footprint
1942 opaqueRegion = visibleRegion;
1943 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001944 }
1945 }
1946
Mathias Agopianab028732010-03-16 16:41:46 -07001947 // Clip the covered region to the visible region
1948 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1949
1950 // Update aboveCoveredLayers for next (lower) layer
1951 aboveCoveredLayers.orSelf(visibleRegion);
1952
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001953 // subtract the opaque region covered by the layers above us
1954 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001955
1956 // compute this layer's dirty region
1957 if (layer->contentDirty) {
1958 // we need to invalidate the whole region
1959 dirty = visibleRegion;
1960 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001961 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001962 layer->contentDirty = false;
1963 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001964 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001965 * the exposed region consists of two components:
1966 * 1) what's VISIBLE now and was COVERED before
1967 * 2) what's EXPOSED now less what was EXPOSED before
1968 *
1969 * note that (1) is conservative, we start with the whole
1970 * visible region but only keep what used to be covered by
1971 * something -- which mean it may have been exposed.
1972 *
1973 * (2) handles areas that were not covered by anything but got
1974 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001975 */
Mathias Agopianab028732010-03-16 16:41:46 -07001976 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001977 const Region oldVisibleRegion = layer->visibleRegion;
1978 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001979 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1980 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981 }
1982 dirty.subtractSelf(aboveOpaqueLayers);
1983
1984 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001985 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986
Mathias Agopianab028732010-03-16 16:41:46 -07001987 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001989
Jesse Halla8026d22012-09-25 13:25:04 -07001990 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001991 layer->setVisibleRegion(visibleRegion);
1992 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001993 layer->setVisibleNonTransparentRegion(
1994 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001995 }
1996
Mathias Agopian87baae12012-07-31 12:38:26 -07001997 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001998}
1999
Mathias Agopian87baae12012-07-31 12:38:26 -07002000void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2001 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002002 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002003 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2004 if (hw->getLayerStack() == layerStack) {
2005 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002006 }
2007 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002008}
2009
Dan Stoza6b9454d2014-11-07 16:00:59 -08002010bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002011{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ALOGV("handlePageFlip");
2013
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002017 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002018 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002019
2020 // Store the set of layers that need updates. This set must not change as
2021 // buffers are being latched, as this could result in a deadlock.
2022 // Example: Two producers share the same command stream and:
2023 // 1.) Layer 0 is latched
2024 // 2.) Layer 0 gets a new frame
2025 // 2.) Layer 1 gets a new frame
2026 // 3.) Layer 1 is latched.
2027 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2028 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002029 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002030 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002031 if (layer->hasQueuedFrame()) {
2032 frameQueued = true;
2033 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002035 } else {
2036 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002037 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002038 } else {
2039 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002040 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002041 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002043 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002044 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002045 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002046 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002047 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002048
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002049 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002050
2051 // If we will need to wake up at some time in the future to deal with a
2052 // queued frame that shouldn't be displayed during this vsync period, wake
2053 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002055 signalLayerUpdate();
2056 }
2057
2058 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060}
2061
Mathias Agopianad456f92011-01-13 17:53:01 -08002062void SurfaceFlinger::invalidateHwcGeometry()
2063{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002065}
2066
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002067
Mathias Agopiancd60f992012-08-16 16:28:27 -07002068void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070{
Dan Stoza71433162014-02-04 16:22:36 -08002071 // We only need to actually compose the display if:
2072 // 1) It is being handled by hardware composer, which may need this to
2073 // keep its virtual display state machine in sync, or
2074 // 2) There is work to be done (the dirty region isn't empty)
2075 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2076 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002078 return;
2079 }
2080
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 ALOGV("doDisplayComposition");
2082
Mathias Agopian87baae12012-07-31 12:38:26 -07002083 Region dirtyRegion(inDirtyRegion);
2084
Mathias Agopianb8a55602009-06-26 19:06:36 -07002085 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002086 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087
Mathias Agopian42977342012-08-05 00:40:46 -07002088 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002089 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002090 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2091 // takes a rectangle, we must make sure to update that whole
2092 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002093 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002094 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002095 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002096 // We need to redraw the rectangle that will be updated
2097 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002098 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002099 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002100 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002101 } else {
2102 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002103 dirtyRegion.set(hw->bounds());
2104 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105 }
2106 }
2107
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002108 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002110 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002111 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002112
2113 // swap buffers (presentation)
2114 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115}
2116
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117bool SurfaceFlinger::doComposeSurfaces(
2118 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002119{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002121
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002123
2124 mat4 oldColorMatrix;
2125 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2126 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2127 if (applyColorMatrix) {
2128 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2129 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2130 }
2131
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2133 if (hasClientComposition) {
2134 ALOGV("hasClientComposition");
2135
2136 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002137 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002139 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2140 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2141 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2142 }
2143 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002144 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002145
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002146 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2148 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002149 // when using overlays, we assume a fully transparent framebuffer
2150 // NOTE: we could reduce how much we need to clear, for instance
2151 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002152 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002153 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002155 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002156 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002158
2159 // we remove the scissor part
2160 // we're left with the letterbox region
2161 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002163
2164 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002166
2167 // but limit it to the dirty region
2168 region.andSelf(dirty);
2169
Mathias Agopianb9494d52012-04-18 02:28:45 -07002170 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002171 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002172 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002174 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002175 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002176
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002178 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002179 // scissor on the main display. It should never be needed
2180 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 const Rect& bounds(displayDevice->getBounds());
2182 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002183 if (scissor != bounds) {
2184 // scissor doesn't match the screen's dimensions, so we
2185 // need to clear everything outside of it and enable
2186 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002187
Mathias Agopianf45c5102012-10-24 16:29:17 -07002188 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 const uint32_t height = displayDevice->getHeight();
2190 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002191 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002192 }
2193 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002194 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002195
Mathias Agopian85d751c2012-08-29 16:59:24 -07002196 /*
2197 * and then, render the layers targeted at the framebuffer
2198 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002199
Dan Stoza9e56aa02015-11-02 13:00:03 -08002200 ALOGV("Rendering client layers");
2201 const Transform& displayTransform = displayDevice->getTransform();
2202 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002203 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204 bool firstLayer = true;
2205 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2206 const Region clip(dirty.intersect(
2207 displayTransform.transform(layer->visibleRegion)));
2208 ALOGV("Layer: %s", layer->getName().string());
2209 ALOGV(" Composition type: %s",
2210 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002211 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 switch (layer->getCompositionType(hwcId)) {
2213 case HWC2::Composition::Cursor:
2214 case HWC2::Composition::Device:
2215 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002216 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2218 layer->isOpaque(state) && (state.alpha == 1.0f)
2219 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220 // never clear the very first layer since we're
2221 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002223 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002224 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 case HWC2::Composition::Client: {
2227 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002228 break;
2229 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002231 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 } else {
2234 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002235 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002237 }
2238 } else {
2239 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002241 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002243 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002245 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002246 }
2247 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002248
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002249 if (applyColorMatrix) {
2250 getRenderEngine().setupColorTransform(oldColorMatrix);
2251 }
2252
Mathias Agopianf45c5102012-10-24 16:29:17 -07002253 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002255 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256}
2257
Mathias Agopian3f844832013-08-07 21:24:32 -07002258void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002259 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002260 RenderEngine& engine(getRenderEngine());
2261 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262}
2263
Dan Stoza7d89d062015-04-30 13:29:25 -07002264status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002265 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002266 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002267 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002268{
Dan Stoza7d89d062015-04-30 13:29:25 -07002269 // add this layer to the current state list
2270 {
2271 Mutex::Autolock _l(mStateLock);
2272 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2273 return NO_MEMORY;
2274 }
2275 mCurrentState.layersSortedByZ.add(lbc);
2276 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2277 }
2278
Mathias Agopian96f08192010-06-02 23:28:45 -07002279 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002280 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002281
Dan Stoza7d89d062015-04-30 13:29:25 -07002282 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002283}
2284
Dan Stozaae56a322016-08-09 23:38:10 +00002285status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002287 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002289 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002290 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002291 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292 return NO_ERROR;
2293 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002294 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295}
2296
Dan Stozac7014012014-02-14 15:03:43 -08002297uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002298 return android_atomic_release_load(&mTransactionFlags);
2299}
2300
Mathias Agopian3f844832013-08-07 21:24:32 -07002301uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2303}
2304
Mathias Agopian3f844832013-08-07 21:24:32 -07002305uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2307 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002308 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309 }
2310 return old;
2311}
2312
Mathias Agopian8b33f032012-07-24 20:43:54 -07002313void SurfaceFlinger::setTransactionState(
2314 const Vector<ComposerState>& state,
2315 const Vector<DisplayState>& displays,
2316 uint32_t flags)
2317{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002318 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002319 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002320 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002321
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002322 if (flags & eAnimation) {
2323 // For window updates that are part of an animation we must wait for
2324 // previous animation "frames" to be handled.
2325 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002326 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002327 if (CC_UNLIKELY(err != NO_ERROR)) {
2328 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002329 // caller after a few seconds.
2330 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2331 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002332 mAnimTransactionPending = false;
2333 break;
2334 }
2335 }
2336 }
2337
Mathias Agopiane57f2922012-08-09 16:29:12 -07002338 size_t count = displays.size();
2339 for (size_t i=0 ; i<count ; i++) {
2340 const DisplayState& s(displays[i]);
2341 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002342 }
2343
Mathias Agopiane57f2922012-08-09 16:29:12 -07002344 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002345 for (size_t i=0 ; i<count ; i++) {
2346 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002347 // Here we need to check that the interface we're given is indeed
2348 // one of our own. A malicious client could give us a NULL
2349 // IInterface, or one of its own or even one of our own but a
2350 // different type. All these situations would cause us to crash.
2351 //
2352 // NOTE: it would be better to use RTTI as we could directly check
2353 // that we have a Client*. however, RTTI is disabled in Android.
2354 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002355 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002356 if (binder != NULL) {
2357 String16 desc(binder->getInterfaceDescriptor());
2358 if (desc == ISurfaceComposerClient::descriptor) {
2359 sp<Client> client( static_cast<Client *>(s.client.get()) );
2360 transactionFlags |= setClientStateLocked(client, s.state);
2361 }
2362 }
2363 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002364 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002365
Robert Carr2a7dbb42016-05-24 11:41:28 -07002366 // If a synchronous transaction is explicitly requested without any changes,
2367 // force a transaction anyway. This can be used as a flush mechanism for
2368 // previous async transactions.
2369 if (transactionFlags == 0 && (flags & eSynchronous)) {
2370 transactionFlags = eTransactionNeeded;
2371 }
2372
Mathias Agopian386aa982011-11-07 21:58:03 -08002373 if (transactionFlags) {
Irvel468051e2016-06-13 16:44:44 -07002374 mInterceptor.saveLayerUpdates(state, flags);
2375
Mathias Agopian386aa982011-11-07 21:58:03 -08002376 // this triggers the transaction
2377 setTransactionFlags(transactionFlags);
2378
2379 // if this is a synchronous transaction, wait for it to take effect
2380 // before returning.
2381 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002382 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002383 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002384 if (flags & eAnimation) {
2385 mAnimTransactionPending = true;
2386 }
2387 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002388 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2389 if (CC_UNLIKELY(err != NO_ERROR)) {
2390 // just in case something goes wrong in SF, return to the
2391 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002392 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2393 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002394 break;
2395 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002396 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397 }
2398}
2399
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2401{
Jesse Hall9a143922012-10-04 16:29:19 -07002402 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2403 if (dpyIdx < 0)
2404 return 0;
2405
Mathias Agopiane57f2922012-08-09 16:29:12 -07002406 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002407 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002408 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002409 const uint32_t what = s.what;
2410 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002411 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002412 disp.surface = s.surface;
2413 flags |= eDisplayTransactionNeeded;
2414 }
2415 }
2416 if (what & DisplayState::eLayerStackChanged) {
2417 if (disp.layerStack != s.layerStack) {
2418 disp.layerStack = s.layerStack;
2419 flags |= eDisplayTransactionNeeded;
2420 }
2421 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002422 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002423 if (disp.orientation != s.orientation) {
2424 disp.orientation = s.orientation;
2425 flags |= eDisplayTransactionNeeded;
2426 }
2427 if (disp.frame != s.frame) {
2428 disp.frame = s.frame;
2429 flags |= eDisplayTransactionNeeded;
2430 }
2431 if (disp.viewport != s.viewport) {
2432 disp.viewport = s.viewport;
2433 flags |= eDisplayTransactionNeeded;
2434 }
2435 }
Michael Lentine47e45402014-07-18 15:34:25 -07002436 if (what & DisplayState::eDisplaySizeChanged) {
2437 if (disp.width != s.width) {
2438 disp.width = s.width;
2439 flags |= eDisplayTransactionNeeded;
2440 }
2441 if (disp.height != s.height) {
2442 disp.height = s.height;
2443 flags |= eDisplayTransactionNeeded;
2444 }
2445 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002446 }
2447 return flags;
2448}
2449
2450uint32_t SurfaceFlinger::setClientStateLocked(
2451 const sp<Client>& client,
2452 const layer_state_t& s)
2453{
2454 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002455 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002456 if (layer != 0) {
2457 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002458 bool geometryAppliesWithResize =
2459 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002460 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002461 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002462 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002463 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002464 }
2465 if (what & layer_state_t::eLayerChanged) {
2466 // NOTE: index needs to be calculated before we update the state
2467 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002468 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 mCurrentState.layersSortedByZ.removeAt(idx);
2470 mCurrentState.layersSortedByZ.add(layer);
2471 // we need traversal (state changed)
2472 // AND transaction (list changed)
2473 flags |= eTransactionNeeded|eTraversalNeeded;
2474 }
2475 }
2476 if (what & layer_state_t::eSizeChanged) {
2477 if (layer->setSize(s.w, s.h)) {
2478 flags |= eTraversalNeeded;
2479 }
2480 }
2481 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002483 flags |= eTraversalNeeded;
2484 }
2485 if (what & layer_state_t::eMatrixChanged) {
2486 if (layer->setMatrix(s.matrix))
2487 flags |= eTraversalNeeded;
2488 }
2489 if (what & layer_state_t::eTransparentRegionChanged) {
2490 if (layer->setTransparentRegionHint(s.transparentRegion))
2491 flags |= eTraversalNeeded;
2492 }
Dan Stoza23116082015-06-18 14:58:39 -07002493 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002494 if (layer->setFlags(s.flags, s.mask))
2495 flags |= eTraversalNeeded;
2496 }
2497 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002498 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 flags |= eTraversalNeeded;
2500 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002501 if (what & layer_state_t::eFinalCropChanged) {
2502 if (layer->setFinalCrop(s.finalCrop))
2503 flags |= eTraversalNeeded;
2504 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002505 if (what & layer_state_t::eLayerStackChanged) {
2506 // NOTE: index needs to be calculated before we update the state
2507 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002508 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002509 mCurrentState.layersSortedByZ.removeAt(idx);
2510 mCurrentState.layersSortedByZ.add(layer);
2511 // we need traversal (state changed)
2512 // AND transaction (list changed)
2513 flags |= eTransactionNeeded|eTraversalNeeded;
2514 }
2515 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002516 if (what & layer_state_t::eDeferTransaction) {
2517 layer->deferTransactionUntil(s.handle, s.frameNumber);
2518 // We don't trigger a traversal here because if no other state is
2519 // changed, we don't want this to cause any more work
2520 }
Robert Carrc3574f72016-03-24 12:19:32 -07002521 if (what & layer_state_t::eOverrideScalingModeChanged) {
2522 layer->setOverrideScalingMode(s.overrideScalingMode);
2523 // We don't trigger a traversal here because if no other state is
2524 // changed, we don't want this to cause any more work
2525 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002526 }
2527 return flags;
2528}
2529
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002530status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002531 const String8& name,
2532 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002533 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2534 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002536 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002537 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002538 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002539 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002540 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002541
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002542 status_t result = NO_ERROR;
2543
2544 sp<Layer> layer;
2545
Mathias Agopian3165cc22012-08-08 19:42:09 -07002546 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2547 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002548 result = createNormalLayer(client,
2549 name, w, h, flags, format,
2550 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002552 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002553 result = createDimLayer(client,
2554 name, w, h, flags,
2555 handle, gbp, &layer);
2556 break;
2557 default:
2558 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 break;
2560 }
2561
Dan Stoza7d89d062015-04-30 13:29:25 -07002562 if (result != NO_ERROR) {
2563 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002565
2566 result = addClientLayer(client, *handle, *gbp, layer);
2567 if (result != NO_ERROR) {
2568 return result;
2569 }
Irvel468051e2016-06-13 16:44:44 -07002570 mInterceptor.saveLayerCreate(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002571
2572 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002573 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574}
2575
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002576status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2577 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2578 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579{
2580 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002581 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 case PIXEL_FORMAT_TRANSPARENT:
2583 case PIXEL_FORMAT_TRANSLUCENT:
2584 format = PIXEL_FORMAT_RGBA_8888;
2585 break;
2586 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002587 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 break;
2589 }
2590
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002591 *outLayer = new Layer(this, client, name, w, h, flags);
2592 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2593 if (err == NO_ERROR) {
2594 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002595 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002597
2598 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2599 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600}
2601
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002602status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2603 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2604 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002606 *outLayer = new LayerDim(this, client, name, w, h, flags);
2607 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002608 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002609 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002610}
2611
Mathias Agopianac9fa422013-02-11 16:40:36 -08002612status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613{
Mathias Agopian67106042013-03-14 19:18:13 -07002614 // called by the window manager when it wants to remove a Layer
2615 status_t err = NO_ERROR;
2616 sp<Layer> l(client->getLayerUser(handle));
2617 if (l != NULL) {
Irvel468051e2016-06-13 16:44:44 -07002618 mInterceptor.saveLayerDelete(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002619 err = removeLayer(l);
2620 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2621 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002622 }
2623 return err;
2624}
2625
Mathias Agopian13127d82013-03-05 17:47:11 -08002626status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002627{
Mathias Agopian67106042013-03-14 19:18:13 -07002628 // called by ~LayerCleaner() when all references to the IBinder (handle)
2629 // are gone
Dan Stozaae56a322016-08-09 23:38:10 +00002630 status_t err = NO_ERROR;
2631 sp<Layer> l(layer.promote());
2632 if (l != NULL) {
2633 err = removeLayer(l);
2634 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2635 "error removing layer=%p (%s)", l.get(), strerror(-err));
2636 }
2637 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638}
2639
Mathias Agopianb60314a2012-04-10 22:09:54 -07002640// ---------------------------------------------------------------------------
2641
Andy McFadden13a082e2012-08-24 10:16:42 -07002642void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002643 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002644 Vector<ComposerState> state;
2645 Vector<DisplayState> displays;
2646 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002647 d.what = DisplayState::eDisplayProjectionChanged |
2648 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002649 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002650 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002651 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002652 d.frame.makeInvalid();
2653 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002654 d.width = 0;
2655 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002656 displays.add(d);
2657 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002658 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002659
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2661 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002662 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002663}
2664
2665void SurfaceFlinger::initializeDisplays() {
2666 class MessageScreenInitialized : public MessageBase {
2667 SurfaceFlinger* flinger;
2668 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002669 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002670 virtual bool handler() {
2671 flinger->onInitializeDisplays();
2672 return true;
2673 }
2674 };
2675 sp<MessageBase> msg = new MessageScreenInitialized(this);
2676 postMessageAsync(msg); // we may be called from main thread, use async message
2677}
2678
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002679void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2680 int mode) {
2681 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2682 this);
2683 int32_t type = hw->getDisplayType();
2684 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002685
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002686 if (mode == currentMode) {
2687 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002688 return;
2689 }
2690
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002691 hw->setPowerMode(mode);
2692 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2693 ALOGW("Trying to set power mode for virtual display");
2694 return;
2695 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002696
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002697 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002698 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002699 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002700 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2701 // FIXME: eventthread only knows about the main display right now
2702 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002703 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002704 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002706 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002707 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002708 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002709
2710 struct sched_param param = {0};
2711 param.sched_priority = 1;
2712 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2713 ALOGW("Couldn't set SCHED_FIFO on display on");
2714 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002715 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002716 // Turn off the display
2717 struct sched_param param = {0};
2718 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2719 ALOGW("Couldn't set SCHED_OTHER on display off");
2720 }
2721
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002722 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002723 disableHardwareVsync(true); // also cancels any in-progress resync
2724
Mathias Agopiancde87a32012-09-13 14:09:01 -07002725 // FIXME: eventthread only knows about the main display right now
2726 mEventThread->onScreenReleased();
2727 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002728
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002729 getHwComposer().setPowerMode(type, mode);
2730 mVisibleRegionsDirty = true;
2731 // from this point on, SF will stop drawing on this display
2732 } else {
2733 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002734 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002735}
2736
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002737void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2738 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002739 SurfaceFlinger& mFlinger;
2740 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002741 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002742 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002743 MessageSetPowerMode(SurfaceFlinger& flinger,
2744 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2745 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002746 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002747 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002748 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002749 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002750 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002751 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002752 ALOGW("Attempt to set power mode = %d for virtual display",
2753 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002754 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002755 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002756 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002757 return true;
2758 }
2759 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002760 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002761 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002762}
2763
2764// ---------------------------------------------------------------------------
2765
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2767{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002769
Mathias Agopianbd115332013-04-18 16:41:04 -07002770 IPCThreadState* ipc = IPCThreadState::self();
2771 const int pid = ipc->getCallingPid();
2772 const int uid = ipc->getCallingUid();
2773 if ((uid != AID_SHELL) &&
2774 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002775 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002776 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002778 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002779 // (this would indicate SF is stuck, but we want to be able to
2780 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002781 status_t err = mStateLock.timedLock(s2ns(1));
2782 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002783 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002784 result.appendFormat(
2785 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2786 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002787 }
2788
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002789 bool dumpAll = true;
2790 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002791 size_t numArgs = args.size();
2792 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002793 if ((index < numArgs) &&
2794 (args[index] == String16("--list"))) {
2795 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002796 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002797 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002798 }
2799
2800 if ((index < numArgs) &&
2801 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002802 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002803 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002804 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002805 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002806
2807 if ((index < numArgs) &&
2808 (args[index] == String16("--latency-clear"))) {
2809 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002810 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002811 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002812 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002813
2814 if ((index < numArgs) &&
2815 (args[index] == String16("--dispsync"))) {
2816 index++;
2817 mPrimaryDispSync.dump(result);
2818 dumpAll = false;
2819 }
Dan Stozab90cf072015-03-05 11:05:59 -08002820
2821 if ((index < numArgs) &&
2822 (args[index] == String16("--static-screen"))) {
2823 index++;
2824 dumpStaticScreenStats(result);
2825 dumpAll = false;
2826 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002827
2828 if ((index < numArgs) &&
2829 (args[index] == String16("--fences"))) {
2830 index++;
2831 mFenceTracker.dump(&result);
2832 dumpAll = false;
2833 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002835
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002836 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002837 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002838 }
2839
Mathias Agopian9795c422009-08-26 16:36:26 -07002840 if (locked) {
2841 mStateLock.unlock();
2842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844 write(fd, result.string(), result.size());
2845 return NO_ERROR;
2846}
2847
Dan Stozac7014012014-02-14 15:03:43 -08002848void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2849 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002850{
2851 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2852 const size_t count = currentLayers.size();
2853 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002854 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002855 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002856 }
2857}
2858
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002859void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002860 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002861{
2862 String8 name;
2863 if (index < args.size()) {
2864 name = String8(args[index]);
2865 index++;
2866 }
2867
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2869 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002870 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002871
2872 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002873 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002874 } else {
2875 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2876 const size_t count = currentLayers.size();
2877 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002878 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002879 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002880 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002881 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002882 }
2883 }
2884}
2885
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002886void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002887 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002888{
2889 String8 name;
2890 if (index < args.size()) {
2891 name = String8(args[index]);
2892 index++;
2893 }
2894
2895 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2896 const size_t count = currentLayers.size();
2897 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002898 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002899 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002900 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002901 }
2902 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002903
Svetoslavd85084b2014-03-20 10:28:31 -07002904 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002905}
2906
Jamie Gennis6547ff42013-07-16 20:12:42 -07002907// This should only be called from the main thread. Otherwise it would need
2908// the lock and should use mCurrentState rather than mDrawingState.
2909void SurfaceFlinger::logFrameStats() {
2910 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2911 const size_t count = drawingLayers.size();
2912 for (size_t i=0 ; i<count ; i++) {
2913 const sp<Layer>& layer(drawingLayers[i]);
2914 layer->logFrameStats();
2915 }
2916
2917 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2918}
2919
Andy McFadden4803b742012-09-24 19:07:20 -07002920/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2921{
2922 static const char* config =
2923 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002924#ifdef HAS_CONTEXT_PRIORITY
2925 " HAS_CONTEXT_PRIORITY"
2926#endif
2927#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2928 " NEVER_DEFAULT_TO_ASYNC_MODE"
2929#endif
2930#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2931 " TARGET_DISABLE_TRIPLE_BUFFERING"
2932#endif
2933 "]";
2934 result.append(config);
2935}
2936
Dan Stozab90cf072015-03-05 11:05:59 -08002937void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2938{
2939 result.appendFormat("Static screen stats:\n");
2940 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2941 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2942 float percent = 100.0f *
2943 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2944 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2945 b + 1, bucketTimeSec, percent);
2946 }
2947 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2948 float percent = 100.0f *
2949 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2950 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2951 NUM_BUCKETS - 1, bucketTimeSec, percent);
2952}
2953
Dan Stozae77c7662016-05-13 11:37:28 -07002954void SurfaceFlinger::recordBufferingStats(const char* layerName,
2955 std::vector<OccupancyTracker::Segment>&& history) {
2956 Mutex::Autolock lock(mBufferingStatsMutex);
2957 auto& stats = mBufferingStats[layerName];
2958 for (const auto& segment : history) {
2959 if (!segment.usedThirdBuffer) {
2960 stats.twoBufferTime += segment.totalTime;
2961 }
2962 if (segment.occupancyAverage < 1.0f) {
2963 stats.doubleBufferedTime += segment.totalTime;
2964 } else if (segment.occupancyAverage < 2.0f) {
2965 stats.tripleBufferedTime += segment.totalTime;
2966 }
2967 ++stats.numSegments;
2968 stats.totalTime += segment.totalTime;
2969 }
2970}
2971
2972void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2973 result.append("Buffering stats:\n");
2974 result.append(" [Layer name] <Active time> <Two buffer> "
2975 "<Double buffered> <Triple buffered>\n");
2976 Mutex::Autolock lock(mBufferingStatsMutex);
2977 typedef std::tuple<std::string, float, float, float> BufferTuple;
2978 std::map<float, BufferTuple, std::greater<float>> sorted;
2979 for (const auto& statsPair : mBufferingStats) {
2980 const char* name = statsPair.first.c_str();
2981 const BufferingStats& stats = statsPair.second;
2982 if (stats.numSegments == 0) {
2983 continue;
2984 }
2985 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2986 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2987 stats.totalTime;
2988 float doubleBufferRatio = static_cast<float>(
2989 stats.doubleBufferedTime) / stats.totalTime;
2990 float tripleBufferRatio = static_cast<float>(
2991 stats.tripleBufferedTime) / stats.totalTime;
2992 sorted.insert({activeTime, {name, twoBufferRatio,
2993 doubleBufferRatio, tripleBufferRatio}});
2994 }
2995 for (const auto& sortedPair : sorted) {
2996 float activeTime = sortedPair.first;
2997 const BufferTuple& values = sortedPair.second;
2998 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2999 std::get<0>(values).c_str(), activeTime,
3000 std::get<1>(values), std::get<2>(values),
3001 std::get<3>(values));
3002 }
3003 result.append("\n");
3004}
3005
3006
Mathias Agopian74d211a2013-04-22 16:55:35 +02003007void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3008 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003009{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003010 bool colorize = false;
3011 if (index < args.size()
3012 && (args[index] == String16("--color"))) {
3013 colorize = true;
3014 index++;
3015 }
3016
3017 Colorizer colorizer(colorize);
3018
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003019 // figure out if we're stuck somewhere
3020 const nsecs_t now = systemTime();
3021 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3022 const nsecs_t inTransaction(mDebugInTransaction);
3023 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3024 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3025
3026 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003027 * Dump library configuration.
3028 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003029
3030 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003031 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003032 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003033 appendSfConfigString(result);
3034 appendUiConfigString(result);
3035 appendGuiConfigString(result);
3036 result.append("\n");
3037
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003038 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003039 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003040 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003041 result.append(SyncFeatures::getInstance().toString());
3042 result.append("\n");
3043
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3045
Andy McFadden41d67d72014-04-25 16:58:34 -07003046 colorizer.bold(result);
3047 result.append("DispSync configuration: ");
3048 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003049 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3050 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3052 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003053 result.append("\n");
3054
Dan Stozab90cf072015-03-05 11:05:59 -08003055 // Dump static screen stats
3056 result.append("\n");
3057 dumpStaticScreenStats(result);
3058 result.append("\n");
3059
Dan Stozae77c7662016-05-13 11:37:28 -07003060 dumpBufferingStats(result);
3061
Andy McFadden4803b742012-09-24 19:07:20 -07003062 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003063 * Dump the visible layer list
3064 */
3065 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3066 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003067 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003068 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003069 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003070 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003071 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003072 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003073 }
3074
3075 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003076 * Dump Display state
3077 */
3078
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003079 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003080 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003081 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003082 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3083 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003084 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003085 }
3086
3087 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003088 * Dump SurfaceFlinger global state
3089 */
3090
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003092 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003093 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003094
Mathias Agopian888c8222012-08-04 21:10:38 -07003095 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003096 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003097
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003098 colorizer.bold(result);
3099 result.appendFormat("EGL implementation : %s\n",
3100 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3101 colorizer.reset(result);
3102 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003103 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003104
Mathias Agopian875d8e12013-06-07 15:35:48 -07003105 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003106
Mathias Agopian42977342012-08-05 00:40:46 -07003107 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003108 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3109 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003111 " last eglSwapBuffers() time: %f us\n"
3112 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003113 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003114 " refresh-rate : %f fps\n"
3115 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003116 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003117 " gpu_to_cpu_unsupported : %d\n"
3118 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003119 mLastSwapBufferTime/1000.0,
3120 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003121 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003122 1e9 / activeConfig->getVsyncPeriod(),
3123 activeConfig->getDpiX(),
3124 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003125 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003126
Mathias Agopian74d211a2013-04-22 16:55:35 +02003127 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003128 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003129
Mathias Agopian74d211a2013-04-22 16:55:35 +02003130 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003131 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003132
3133 /*
3134 * VSYNC state
3135 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003136 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003137
3138 /*
3139 * Dump HWComposer state
3140 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003141 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003142 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003143 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003144 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003145 result.appendFormat(" h/w composer %s\n",
3146 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003147 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003148
3149 /*
3150 * Dump gralloc state
3151 */
3152 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3153 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003154}
3155
Mathias Agopian13127d82013-03-05 17:47:11 -08003156const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003157SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003158 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003159 wp<IBinder> dpy;
3160 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3161 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3162 dpy = mDisplays.keyAt(i);
3163 break;
3164 }
3165 }
3166 if (dpy == NULL) {
3167 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3168 // Just use the primary display so we have something to return
3169 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3170 }
3171 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003172}
3173
Keun young Park63f165f2012-08-31 10:53:36 -07003174bool SurfaceFlinger::startDdmConnection()
3175{
3176 void* libddmconnection_dso =
3177 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3178 if (!libddmconnection_dso) {
3179 return false;
3180 }
3181 void (*DdmConnection_start)(const char* name);
3182 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003183 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003184 if (!DdmConnection_start) {
3185 dlclose(libddmconnection_dso);
3186 return false;
3187 }
3188 (*DdmConnection_start)(getServiceName());
3189 return true;
3190}
3191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192status_t SurfaceFlinger::onTransact(
3193 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3194{
3195 switch (code) {
3196 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003197 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003198 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003200 case CLEAR_ANIMATION_FRAME_STATS:
3201 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003202 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003203 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 {
3205 // codes that require permission check
3206 IPCThreadState* ipc = IPCThreadState::self();
3207 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003208 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003209 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003210 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003211 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003212 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3213 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003215 break;
3216 }
3217 case CAPTURE_SCREEN:
3218 {
3219 // codes that require permission check
3220 IPCThreadState* ipc = IPCThreadState::self();
3221 const int pid = ipc->getCallingPid();
3222 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003223 if ((uid != AID_GRAPHICS) &&
3224 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003225 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003226 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3227 return PERMISSION_DENIED;
3228 }
3229 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 }
3231 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3234 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003235 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003236 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003237 IPCThreadState* ipc = IPCThreadState::self();
3238 const int pid = ipc->getCallingPid();
3239 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003240 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003241 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 return PERMISSION_DENIED;
3243 }
3244 int n;
3245 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003246 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003247 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 return NO_ERROR;
3249 case 1002: // SHOW_UPDATES
3250 n = data.readInt32();
3251 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003252 invalidateHwcGeometry();
3253 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003256 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003257 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003259 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003260 setTransactionFlags(
3261 eTransactionNeeded|
3262 eDisplayTransactionNeeded|
3263 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003264 return NO_ERROR;
3265 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003266 case 1006:{ // send empty update
3267 signalRefresh();
3268 return NO_ERROR;
3269 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003270 case 1008: // toggle use of hw composer
3271 n = data.readInt32();
3272 mDebugDisableHWC = n ? 1 : 0;
3273 invalidateHwcGeometry();
3274 repaintEverything();
3275 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003276 case 1009: // toggle use of transform hint
3277 n = data.readInt32();
3278 mDebugDisableTransformHint = n ? 1 : 0;
3279 invalidateHwcGeometry();
3280 repaintEverything();
3281 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003283 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284 reply->writeInt32(0);
3285 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003286 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003287 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288 return NO_ERROR;
3289 case 1013: {
3290 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003291 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3292 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003293 return NO_ERROR;
3294 }
3295 case 1014: {
3296 // daltonize
3297 n = data.readInt32();
3298 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003299 case 1:
3300 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3301 break;
3302 case 2:
3303 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3304 break;
3305 case 3:
3306 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3307 break;
3308 default:
3309 mDaltonizer.setType(ColorBlindnessType::None);
3310 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003311 }
3312 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003313 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003314 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003315 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003316 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003317 invalidateHwcGeometry();
3318 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003319 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003320 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003321 case 1015: {
3322 // apply a color matrix
3323 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003324 if (n) {
3325 // color matrix is sent as mat3 matrix followed by vec3
3326 // offset, then packed into a mat4 where the last row is
3327 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003328 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003329 for (size_t j = 0; j < 4; j++) {
3330 mColorMatrix[i][j] = data.readFloat();
3331 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003332 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003333 } else {
3334 mColorMatrix = mat4();
3335 }
3336 invalidateHwcGeometry();
3337 repaintEverything();
3338 return NO_ERROR;
3339 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003340 // This is an experimental interface
3341 // Needs to be shifted to proper binder interface when we productize
3342 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003343 n = data.readInt32();
3344 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003345 return NO_ERROR;
3346 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003347 case 1017: {
3348 n = data.readInt32();
3349 mForceFullDamage = static_cast<bool>(n);
3350 return NO_ERROR;
3351 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003352 case 1018: { // Modify Choreographer's phase offset
3353 n = data.readInt32();
3354 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3355 return NO_ERROR;
3356 }
3357 case 1019: { // Modify SurfaceFlinger's phase offset
3358 n = data.readInt32();
3359 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3360 return NO_ERROR;
3361 }
Irvel468051e2016-06-13 16:44:44 -07003362 case 1020: { // Layer updates interceptor
3363 n = data.readInt32();
3364 if (n) {
3365 ALOGV("Interceptor enabled");
3366 mInterceptor.enable(mDrawingState.layersSortedByZ);
3367 }
3368 else{
3369 ALOGV("Interceptor disabled");
3370 mInterceptor.disable();
3371 }
3372 return NO_ERROR;
3373 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003374 case 1021: { // Disable HWC virtual displays
3375 n = data.readInt32();
3376 mUseHwcVirtualDisplays = !n;
3377 return NO_ERROR;
3378 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379 }
3380 }
3381 return err;
3382}
3383
Mathias Agopian53331da2011-08-22 21:44:41 -07003384void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003385 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003386 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003387}
3388
Mathias Agopian59119e62010-10-11 12:37:43 -07003389// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003390// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003391// ---------------------------------------------------------------------------
3392
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003393/* The code below is here to handle b/8734824
3394 *
3395 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003396 * from the surfaceflinger thread to the calling binder thread, where they
3397 * are executed. This allows the calling thread in the calling process to be
3398 * reused and not depend on having "enough" binder threads to handle the
3399 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003400 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003401class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003402 /* Parts of GraphicProducerWrapper are run on two different threads,
3403 * communicating by sending messages via Looper but also by shared member
3404 * data. Coherence maintenance is subtle and in places implicit (ugh).
3405 *
3406 * Don't rely on Looper's sendMessage/handleMessage providing
3407 * release/acquire semantics for any data not actually in the Message.
3408 * Data going from surfaceflinger to binder threads needs to be
3409 * synchronized explicitly.
3410 *
3411 * Barrier open/wait do provide release/acquire semantics. This provides
3412 * implicit synchronization for data coming back from binder to
3413 * surfaceflinger threads.
3414 */
3415
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003416 sp<IGraphicBufferProducer> impl;
3417 sp<Looper> looper;
3418 status_t result;
3419 bool exitPending;
3420 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003421 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003422 uint32_t code;
3423 Parcel const* data;
3424 Parcel* reply;
3425
3426 enum {
3427 MSG_API_CALL,
3428 MSG_EXIT
3429 };
3430
3431 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003432 * Called on surfaceflinger thread. This is called by our "fake"
3433 * BpGraphicBufferProducer. We package the data and reply Parcel and
3434 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003435 */
3436 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003437 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003438 this->code = code;
3439 this->data = &data;
3440 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003441 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003442 // if we've exited, we run the message synchronously right here.
3443 // note (JH): as far as I can tell from looking at the code, this
3444 // never actually happens. if it does, i'm not sure if it happens
3445 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003446 handleMessage(Message(MSG_API_CALL));
3447 } else {
3448 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003449 // Prevent stores to this->{code, data, reply} from being
3450 // reordered later than the construction of Message.
3451 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003452 looper->sendMessage(this, Message(MSG_API_CALL));
3453 barrier.wait();
3454 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003455 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003456 }
3457
3458 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003459 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003460 * call the real BpGraphicBufferProducer.
3461 */
3462 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003463 int what = message.what;
3464 // Prevent reads below from happening before the read from Message
3465 atomic_thread_fence(memory_order_acquire);
3466 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003467 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003468 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003469 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003470 exitRequested = true;
3471 }
3472 }
3473
3474public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003475 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003476 : impl(impl),
3477 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003478 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003479 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003480 exitRequested(false),
3481 code(0),
3482 data(NULL),
3483 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003484 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003485
Jesse Hallb154c422014-07-13 12:47:02 -07003486 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003487 status_t waitForResponse() {
3488 do {
3489 looper->pollOnce(-1);
3490 } while (!exitRequested);
3491 return result;
3492 }
3493
Jesse Hallb154c422014-07-13 12:47:02 -07003494 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003495 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003496 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003497 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003498 // Ensure this->result is visible to the binder thread before it
3499 // handles the message.
3500 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003501 looper->sendMessage(this, Message(MSG_EXIT));
3502 }
3503};
3504
3505
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003506status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3507 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003508 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003509 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003510 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003511
3512 if (CC_UNLIKELY(display == 0))
3513 return BAD_VALUE;
3514
3515 if (CC_UNLIKELY(producer == 0))
3516 return BAD_VALUE;
3517
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003518 // if we have secure windows on this display, never allow the screen capture
3519 // unless the producer interface is local (i.e.: we can take a screenshot for
3520 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003521 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003522
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003523 // Convert to surfaceflinger's internal rotation type.
3524 Transform::orientation_flags rotationFlags;
3525 switch (rotation) {
3526 case ISurfaceComposer::eRotateNone:
3527 rotationFlags = Transform::ROT_0;
3528 break;
3529 case ISurfaceComposer::eRotate90:
3530 rotationFlags = Transform::ROT_90;
3531 break;
3532 case ISurfaceComposer::eRotate180:
3533 rotationFlags = Transform::ROT_180;
3534 break;
3535 case ISurfaceComposer::eRotate270:
3536 rotationFlags = Transform::ROT_270;
3537 break;
3538 default:
3539 rotationFlags = Transform::ROT_0;
3540 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3541 break;
3542 }
3543
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003544 class MessageCaptureScreen : public MessageBase {
3545 SurfaceFlinger* flinger;
3546 sp<IBinder> display;
3547 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003548 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003549 uint32_t reqWidth, reqHeight;
3550 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003551 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003552 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003553 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003554 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003555 public:
3556 MessageCaptureScreen(SurfaceFlinger* flinger,
3557 const sp<IBinder>& display,
3558 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003559 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003560 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003561 bool useIdentityTransform,
3562 Transform::orientation_flags rotation,
3563 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003564 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003565 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003566 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003567 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003568 rotation(rotation), result(PERMISSION_DENIED),
3569 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003570 {
3571 }
3572 status_t getResult() const {
3573 return result;
3574 }
3575 virtual bool handler() {
3576 Mutex::Autolock _l(flinger->mStateLock);
3577 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003578 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003579 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003580 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003581 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003582 return true;
3583 }
3584 };
3585
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003586 // this creates a "fake" BBinder which will serve as a "fake" remote
3587 // binder to receive the marshaled calls and forward them to the
3588 // real remote (a BpGraphicBufferProducer)
3589 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3590
3591 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3592 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003593 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003594 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003595 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003596 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003597
3598 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003599 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003600 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003601 }
3602 return res;
3603}
3604
Mathias Agopian180f10d2013-04-10 22:55:41 -07003605
3606void SurfaceFlinger::renderScreenImplLocked(
3607 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003608 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003609 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003610 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003611{
3612 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003613 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003614
3615 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003616 const int32_t hw_w = hw->getWidth();
3617 const int32_t hw_h = hw->getHeight();
3618 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003619 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003620
Dan Stozac1879002014-05-22 15:59:05 -07003621 // if a default or invalid sourceCrop is passed in, set reasonable values
3622 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3623 !sourceCrop.isValid()) {
3624 sourceCrop.setLeftTop(Point(0, 0));
3625 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3626 }
3627
3628 // ensure that sourceCrop is inside screen
3629 if (sourceCrop.left < 0) {
3630 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3631 }
Dan Stozabe31f442014-06-11 11:20:54 -07003632 if (sourceCrop.right > hw_w) {
3633 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003634 }
3635 if (sourceCrop.top < 0) {
3636 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3637 }
Dan Stozabe31f442014-06-11 11:20:54 -07003638 if (sourceCrop.bottom > hw_h) {
3639 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003640 }
3641
Mathias Agopian180f10d2013-04-10 22:55:41 -07003642 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003643 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003644
3645 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003646 engine.setViewportAndProjection(
3647 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003648 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003649
3650 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003651 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003652
3653 const LayerVector& layers( mDrawingState.layersSortedByZ );
3654 const size_t count = layers.size();
3655 for (size_t i=0 ; i<count ; ++i) {
3656 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003657 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003658 if (state.layerStack == hw->getLayerStack()) {
3659 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3660 if (layer->isVisible()) {
3661 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003662 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003663 if (filtering) layer->setFiltering(false);
3664 }
3665 }
3666 }
3667 }
3668
Mathias Agopian931bda12013-08-28 18:11:46 -07003669 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003670}
3671
3672
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003673status_t SurfaceFlinger::captureScreenImplLocked(
3674 const sp<const DisplayDevice>& hw,
3675 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003676 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003677 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003678 bool useIdentityTransform, Transform::orientation_flags rotation,
3679 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003680{
3681 ATRACE_CALL();
3682
Mathias Agopian180f10d2013-04-10 22:55:41 -07003683 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003684 uint32_t hw_w = hw->getWidth();
3685 uint32_t hw_h = hw->getHeight();
3686
3687 if (rotation & Transform::ROT_90) {
3688 std::swap(hw_w, hw_h);
3689 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003690
Mathias Agopian180f10d2013-04-10 22:55:41 -07003691 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3692 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3693 reqWidth, reqHeight, hw_w, hw_h);
3694 return BAD_VALUE;
3695 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003696
Mathias Agopian180f10d2013-04-10 22:55:41 -07003697 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3698 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3699
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003700 bool secureLayerIsVisible = false;
3701 const LayerVector& layers(mDrawingState.layersSortedByZ);
3702 const size_t count = layers.size();
3703 for (size_t i = 0 ; i < count ; ++i) {
3704 const sp<Layer>& layer(layers[i]);
3705 const Layer::State& state(layer->getDrawingState());
3706 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3707 state.z <= maxLayerZ && layer->isVisible() &&
3708 layer->isSecure()) {
3709 secureLayerIsVisible = true;
3710 }
3711 }
3712
3713 if (!isLocalScreenshot && secureLayerIsVisible) {
3714 ALOGW("FB is protected: PERMISSION_DENIED");
3715 return PERMISSION_DENIED;
3716 }
3717
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003718 // create a surface (because we're a producer, and we need to
3719 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003720 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003721
3722 // Put the screenshot Surface into async mode so that
3723 // Layer::headFenceHasSignaled will always return true and we'll latch the
3724 // first buffer regardless of whether or not its acquire fence has
3725 // signaled. This is needed to avoid a race condition in the rotation
3726 // animation. See b/30209608
3727 sur->setAsyncMode(true);
3728
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003729 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003730
Michael Lentine5a16a622015-05-21 13:48:24 -07003731 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3732 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003733 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3734 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003735
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003736 int err = 0;
3737 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003738 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003739 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3740 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003741
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003742 if (err == NO_ERROR) {
3743 ANativeWindowBuffer* buffer;
3744 /* TODO: Once we have the sync framework everywhere this can use
3745 * server-side waits on the fence that dequeueBuffer returns.
3746 */
3747 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3748 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003749 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003750 // create an EGLImage from the buffer so we can later
3751 // turn it into a texture
3752 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3753 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3754 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003755 // this binds the given EGLImage as a framebuffer for the
3756 // duration of this scope.
3757 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3758 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003759 // this will in fact render into our dequeued buffer
3760 // via an FBO, which means we didn't have to create
3761 // an EGLSurface and therefore we're not
3762 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003763 renderScreenImplLocked(
3764 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3765 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003766
Riley Andrews86639902014-08-15 12:27:24 -07003767 // Attempt to create a sync khr object that can produce a sync point. If that
3768 // isn't available, create a non-dupable sync object in the fallback path and
3769 // wait on it directly.
3770 EGLSyncKHR sync;
3771 if (!DEBUG_SCREENSHOTS) {
3772 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003773 // native fence fd will not be populated until flush() is done.
3774 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003775 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003776 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003777 }
Riley Andrews86639902014-08-15 12:27:24 -07003778 if (sync != EGL_NO_SYNC_KHR) {
3779 // get the sync fd
3780 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3781 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3782 ALOGW("captureScreen: failed to dup sync khr object");
3783 syncFd = -1;
3784 }
3785 eglDestroySyncKHR(mEGLDisplay, sync);
3786 } else {
3787 // fallback path
3788 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3789 if (sync != EGL_NO_SYNC_KHR) {
3790 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3791 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3792 EGLint eglErr = eglGetError();
3793 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3794 ALOGW("captureScreen: fence wait timed out");
3795 } else {
3796 ALOGW_IF(eglErr != EGL_SUCCESS,
3797 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3798 }
3799 eglDestroySyncKHR(mEGLDisplay, sync);
3800 } else {
3801 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3802 }
3803 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003804 if (DEBUG_SCREENSHOTS) {
3805 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3806 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3807 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3808 hw, minLayerZ, maxLayerZ);
3809 delete [] pixels;
3810 }
3811
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003812 } else {
3813 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3814 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003815 window->cancelBuffer(window, buffer, syncFd);
3816 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003817 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003818 // destroy our image
3819 eglDestroyImageKHR(mEGLDisplay, image);
3820 } else {
3821 result = BAD_VALUE;
3822 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003823 if (buffer) {
3824 // queueBuffer takes ownership of syncFd
3825 result = window->queueBuffer(window, buffer, syncFd);
3826 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003827 }
3828 } else {
3829 result = BAD_VALUE;
3830 }
3831 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3832 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003833
Mathias Agopian74c40c02010-09-29 13:02:36 -07003834 return result;
3835}
3836
Mathias Agopiand5556842013-09-19 17:08:37 -07003837void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3838 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003839 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003840 for (size_t y=0 ; y<h ; y++) {
3841 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3842 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003843 if (p[x] != 0xFF000000) return;
3844 }
3845 }
3846 ALOGE("*** we just took a black screenshot ***\n"
3847 "requested minz=%d, maxz=%d, layerStack=%d",
3848 minLayerZ, maxLayerZ, hw->getLayerStack());
3849 const LayerVector& layers( mDrawingState.layersSortedByZ );
3850 const size_t count = layers.size();
3851 for (size_t i=0 ; i<count ; ++i) {
3852 const sp<Layer>& layer(layers[i]);
3853 const Layer::State& state(layer->getDrawingState());
3854 const bool visible = (state.layerStack == hw->getLayerStack())
3855 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3856 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003857 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003858 visible ? '+' : '-',
3859 i, layer->getName().string(), state.layerStack, state.z,
3860 layer->isVisible(), state.flags, state.alpha);
3861 }
3862 }
3863}
3864
Pablo Ceballosce796e72016-02-04 19:10:51 -08003865bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3866 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3867 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3868}
3869
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003870// ---------------------------------------------------------------------------
3871
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003872SurfaceFlinger::LayerVector::LayerVector() {
3873}
3874
3875SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003876 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003877}
3878
3879int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3880 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003881{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003882 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003883 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3884 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003885
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003886 uint32_t ls = l->getCurrentState().layerStack;
3887 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003888 if (ls != rs)
3889 return ls - rs;
3890
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003891 uint32_t lz = l->getCurrentState().z;
3892 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003893 if (lz != rz)
3894 return lz - rz;
3895
3896 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003897}
3898
3899// ---------------------------------------------------------------------------
3900
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003901SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003902 : type(DisplayDevice::DISPLAY_ID_INVALID),
3903 layerStack(DisplayDevice::NO_LAYER_STACK),
3904 orientation(0),
3905 width(0),
3906 height(0),
3907 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003908}
3909
Pablo Ceballos53390e12015-08-04 11:25:59 -07003910SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3911 DisplayDevice::DisplayType type, bool isSecure)
3912 : type(type),
3913 layerStack(DisplayDevice::NO_LAYER_STACK),
3914 orientation(0),
3915 width(0),
3916 height(0),
3917 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003918 viewport.makeInvalid();
3919 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003920}
3921
3922// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003925
3926
3927#if defined(__gl_h_)
3928#error "don't include gl/gl.h in this file"
3929#endif
3930
3931#if defined(__gl2_h_)
3932#error "don't include gl2/gl2.h in this file"
3933#endif