blob: 5c7db2b32f9c4f9a7d588f2e0c0f938402eb54af [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>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700155 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
160 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Steve Blocka19954a2012-01-04 20:05:49 +0000162 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163
164 // debugging stuff...
165 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700166
Mathias Agopianb4b17302013-03-20 18:36:41 -0700167 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700168 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700169
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 property_get("debug.sf.showupdates", value, "0");
171 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 property_get("debug.sf.ddms", value, "0");
174 mDebugDDMS = atoi(value);
175 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700176 if (!startDdmConnection()) {
177 // start failed, and DDMS debugging not enabled
178 mDebugDDMS = 0;
179 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700181 ALOGI_IF(mDebugRegion, "showupdates enabled");
182 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183}
184
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800185void SurfaceFlinger::onFirstRef()
186{
187 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800188}
189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190SurfaceFlinger::~SurfaceFlinger()
191{
Mathias Agopiana4912602012-07-12 14:25:33 -0700192 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
193 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
194 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195}
196
Dan Stozac7014012014-02-14 15:03:43 -0800197void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800198{
199 // the window manager died on us. prepare its eulogy.
200
Andy McFadden13a082e2012-08-24 10:16:42 -0700201 // restore initial conditions (default device unblank, etc)
202 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800203
204 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700205 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800206}
207
Mathias Agopian7e27f052010-05-28 14:22:23 -0700208sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209{
Mathias Agopian96f08192010-06-02 23:28:45 -0700210 sp<ISurfaceComposerClient> bclient;
211 sp<Client> client(new Client(this));
212 status_t err = client->initCheck();
213 if (err == NO_ERROR) {
214 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 return bclient;
217}
218
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700219sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
220 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700221{
222 class DisplayToken : public BBinder {
223 sp<SurfaceFlinger> flinger;
224 virtual ~DisplayToken() {
225 // no more references, this display must be terminated
226 Mutex::Autolock _l(flinger->mStateLock);
227 flinger->mCurrentState.displays.removeItem(this);
228 flinger->setTransactionFlags(eDisplayTransactionNeeded);
229 }
230 public:
231 DisplayToken(const sp<SurfaceFlinger>& flinger)
232 : flinger(flinger) {
233 }
234 };
235
236 sp<BBinder> token = new DisplayToken(this);
237
238 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700239 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700240 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241 mCurrentState.displays.add(token, info);
242
243 return token;
244}
245
Jesse Hall6c913be2013-08-08 12:15:49 -0700246void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
247 Mutex::Autolock _l(mStateLock);
248
249 ssize_t idx = mCurrentState.displays.indexOfKey(display);
250 if (idx < 0) {
251 ALOGW("destroyDisplay: invalid display token");
252 return;
253 }
254
255 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
256 if (!info.isVirtualDisplay()) {
257 ALOGE("destroyDisplay called for non-virtual display");
258 return;
259 }
260
261 mCurrentState.displays.removeItemsAt(idx);
262 setTransactionFlags(eDisplayTransactionNeeded);
263}
264
Jesse Hall692c7232012-11-08 15:41:56 -0800265void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800266 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800267 ALOGW_IF(mBuiltinDisplays[type],
268 "Overwriting display token for display type %d", type);
269 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800270 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700271 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800272 mCurrentState.displays.add(mBuiltinDisplays[type], info);
273}
274
Mathias Agopiane57f2922012-08-09 16:29:12 -0700275sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700276 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
278 return NULL;
279 }
Jesse Hall692c7232012-11-08 15:41:56 -0800280 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281}
282
Jamie Gennis9a78c902011-01-12 18:30:40 -0800283sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
284{
285 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
286 return gba;
287}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289void SurfaceFlinger::bootFinished()
290{
291 const nsecs_t now = systemTime();
292 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000293 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700294 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700295
296 // wait patiently for the window manager death
297 const String16 name("window");
298 sp<IBinder> window(defaultServiceManager()->getService(name));
299 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700300 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700301 }
302
303 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700304 // formerly we would just kill the process, but we now ask it to exit so it
305 // can choose where to stop the animation.
306 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700307
308 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
309 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
310 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311}
312
Mathias Agopian3f844832013-08-07 21:24:32 -0700313void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700314 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700315 RenderEngine& engine;
316 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700317 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700318 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
319 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700320 }
321 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700322 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700323 return true;
324 }
325 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700326 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700327}
328
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700329class DispSyncSource : public VSyncSource, private DispSync::Callback {
330public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700331 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000332 const char* name) :
333 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700334 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700335 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000336 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
337 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700338 mDispSync(dispSync),
339 mCallbackMutex(),
340 mCallback(),
341 mVsyncMutex(),
342 mPhaseOffset(phaseOffset),
343 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700344
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700345 virtual ~DispSyncSource() {}
346
347 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700348 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700349 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000350 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700351 static_cast<DispSync::Callback*>(this));
352 if (err != NO_ERROR) {
353 ALOGE("error registering vsync callback: %s (%d)",
354 strerror(-err), err);
355 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700356 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700357 } else {
358 status_t err = mDispSync->removeEventListener(
359 static_cast<DispSync::Callback*>(this));
360 if (err != NO_ERROR) {
361 ALOGE("error unregistering vsync callback: %s (%d)",
362 strerror(-err), err);
363 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700364 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700366 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 }
368
369 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700370 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700371 mCallback = callback;
372 }
373
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700374 virtual void setPhaseOffset(nsecs_t phaseOffset) {
375 Mutex::Autolock lock(mVsyncMutex);
376
377 // Normalize phaseOffset to [0, period)
378 auto period = mDispSync->getPeriod();
379 phaseOffset %= period;
380 if (phaseOffset < 0) {
381 // If we're here, then phaseOffset is in (-period, 0). After this
382 // operation, it will be in (0, period)
383 phaseOffset += period;
384 }
385 mPhaseOffset = phaseOffset;
386
387 // If we're not enabled, we don't need to mess with the listeners
388 if (!mEnabled) {
389 return;
390 }
391
392 // Remove the listener with the old offset
393 status_t err = mDispSync->removeEventListener(
394 static_cast<DispSync::Callback*>(this));
395 if (err != NO_ERROR) {
396 ALOGE("error unregistering vsync callback: %s (%d)",
397 strerror(-err), err);
398 }
399
400 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000401 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700402 static_cast<DispSync::Callback*>(this));
403 if (err != NO_ERROR) {
404 ALOGE("error registering vsync callback: %s (%d)",
405 strerror(-err), err);
406 }
407 }
408
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409private:
410 virtual void onDispSyncEvent(nsecs_t when) {
411 sp<VSyncSource::Callback> callback;
412 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700413 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 callback = mCallback;
415
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700416 if (mTraceVsync) {
417 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700418 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700419 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 }
421
422 if (callback != NULL) {
423 callback->onVSyncEvent(when);
424 }
425 }
426
Tim Murray4a4e4a22016-04-19 16:29:23 +0000427 const char* const mName;
428
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 int mValue;
430
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700431 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700432 const String8 mVsyncOnLabel;
433 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700434
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436
437 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439
440 Mutex mVsyncMutex; // Protects the following
441 nsecs_t mPhaseOffset;
442 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443};
444
445void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700446 ALOGI( "SurfaceFlinger's main thread ready to run. "
447 "Initializing graphics H/W...");
448
Dan Stoza9e56aa02015-11-02 13:00:03 -0800449 { // Autolock scope
450 Mutex::Autolock _l(mStateLock);
451
452 // initialize EGL for the default display
453 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
454 eglInitialize(mEGLDisplay, NULL, NULL);
455
456 // start the EventThread
457 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
458 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800460 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
461 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000462 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800463 mEventQueue.setEventThread(mSFEventThread);
464
Tim Murray41a38532016-06-22 12:42:10 -0700465 // set EventThread and SFEventThread to SCHED_FIFO for minimum jitter
466 struct sched_param param = {0};
467 param.sched_priority = 1;
468 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
469 ALOGE("Couldn't set SCHED_FIFO for EventThread");
470 }
471
472 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
473 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
474 }
475
476
Dan Stoza9e56aa02015-11-02 13:00:03 -0800477 // Get a RenderEngine for the given display / config (can't fail)
478 mRenderEngine = RenderEngine::create(mEGLDisplay,
479 HAL_PIXEL_FORMAT_RGBA_8888);
480 }
481
482 // Drop the state lock while we initialize the hardware composer. We drop
483 // the lock because on creation, it will call back into SurfaceFlinger to
484 // initialize the primary display.
485 mHwc = new HWComposer(this);
486 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
487
Jesse Hall692c7232012-11-08 15:41:56 -0800488 Mutex::Autolock _l(mStateLock);
489
Mathias Agopian875d8e12013-06-07 15:35:48 -0700490 // retrieve the EGL context that was selected/created
491 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700492
Mathias Agopianda27af92012-09-13 18:17:13 -0700493 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
494 "couldn't create EGLContext");
495
Dan Stoza9e56aa02015-11-02 13:00:03 -0800496 // make the GLContext current so that we can create textures when creating
497 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700498 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
499
Jamie Gennisd1700752013-10-14 12:22:52 -0700500 mEventControlThread = new EventControlThread(this);
501 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
502
Mathias Agopian92a979a2012-08-02 18:32:23 -0700503 // initialize our drawing state
504 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700505
Andy McFadden13a082e2012-08-24 10:16:42 -0700506 // set initial conditions (e.g. unblank default device)
507 initializeDisplays();
508
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700509 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700510 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511
Dan Stoza9e56aa02015-11-02 13:00:03 -0800512 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700513}
514
Mathias Agopiana67e4182012-06-19 17:26:12 -0700515void SurfaceFlinger::startBootAnim() {
516 // start boot animation
517 property_set("service.bootanim.exit", "0");
518 property_set("ctl.start", "bootanim");
519}
520
Mathias Agopian875d8e12013-06-07 15:35:48 -0700521size_t SurfaceFlinger::getMaxTextureSize() const {
522 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700523}
524
Mathias Agopian875d8e12013-06-07 15:35:48 -0700525size_t SurfaceFlinger::getMaxViewportDims() const {
526 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800530
Jamie Gennis582270d2011-08-17 18:19:00 -0700531bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800532 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800533 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800534 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700535 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800536}
537
Dan Stoza7f7da322014-05-02 15:26:25 -0700538status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
539 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700540 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700541 return BAD_VALUE;
542 }
543
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500544 if (!display.get())
545 return NAME_NOT_FOUND;
546
Jesse Hall692c7232012-11-08 15:41:56 -0800547 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700548 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800549 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700550 type = i;
551 break;
552 }
553 }
554
555 if (type < 0) {
556 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700557 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700558
Mathias Agopian8b736f12012-08-13 17:54:26 -0700559 // TODO: Not sure if display density should handled by SF any longer
560 class Density {
561 static int getDensityFromProperty(char const* propName) {
562 char property[PROPERTY_VALUE_MAX];
563 int density = 0;
564 if (property_get(propName, property, NULL) > 0) {
565 density = atoi(property);
566 }
567 return density;
568 }
569 public:
570 static int getEmuDensity() {
571 return getDensityFromProperty("qemu.sf.lcd_density"); }
572 static int getBuildDensity() {
573 return getDensityFromProperty("ro.sf.lcd_density"); }
574 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700575
Dan Stoza7f7da322014-05-02 15:26:25 -0700576 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700577
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700579 DisplayInfo info = DisplayInfo();
580
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 float xdpi = hwConfig->getDpiX();
582 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700583
584 if (type == DisplayDevice::DISPLAY_PRIMARY) {
585 // The density of the device is provided by a build property
586 float density = Density::getBuildDensity() / 160.0f;
587 if (density == 0) {
588 // the build doesn't provide a density -- this is wrong!
589 // use xdpi instead
590 ALOGE("ro.sf.lcd_density must be defined as a build property");
591 density = xdpi / 160.0f;
592 }
593 if (Density::getEmuDensity()) {
594 // if "qemu.sf.lcd_density" is specified, it overrides everything
595 xdpi = ydpi = density = Density::getEmuDensity();
596 density /= 160.0f;
597 }
598 info.density = density;
599
600 // TODO: this needs to go away (currently needed only by webkit)
601 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
602 info.orientation = hw->getOrientation();
603 } else {
604 // TODO: where should this value come from?
605 static const int TV_DENSITY = 213;
606 info.density = TV_DENSITY / 160.0f;
607 info.orientation = 0;
608 }
609
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 info.w = hwConfig->getWidth();
611 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700612 info.xdpi = xdpi;
613 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700615 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800616
Andy McFadden91b2ca82014-06-13 14:04:23 -0700617 // This is how far in advance a buffer must be queued for
618 // presentation at a given time. If you want a buffer to appear
619 // on the screen at time N, you must submit the buffer before
620 // (N - presentationDeadline).
621 //
622 // Normally it's one full refresh period (to give SF a chance to
623 // latch the buffer), but this can be reduced by configuring a
624 // DispSync offset. Any additional delays introduced by the hardware
625 // composer or panel must be accounted for here.
626 //
627 // We add an additional 1ms to allow for processing time and
628 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800629 info.presentationDeadline = hwConfig->getVsyncPeriod() -
630 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700631
632 // All non-virtual displays are currently considered secure.
633 info.secure = true;
634
Courtney Goeltzenleuchterfad9d8c2016-06-23 11:49:50 -0600635 // DisplayManager expects each color mode to be its own display
636 // info record.
637 std::vector<int32_t> modes = getHwComposer().getColorModes(type);
638
639 if (modes.size() == 0) {
640 info.colorTransform = 0;
641 configs->push_back(info);
642 }
643 for (int32_t mode : modes) {
644 info.colorTransform = mode;
645 configs->push_back(info);
646 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700647 }
648
Dan Stoza7f7da322014-05-02 15:26:25 -0700649 return NO_ERROR;
650}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700651
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800652status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700653 DisplayStatInfo* stats) {
654 if (stats == NULL) {
655 return BAD_VALUE;
656 }
657
658 // FIXME for now we always return stats for the primary display
659 memset(stats, 0, sizeof(*stats));
660 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
661 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
662 return NO_ERROR;
663}
664
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700665int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700666 sp<DisplayDevice> device(getDisplayDevice(display));
667 if (device != NULL) {
668 return device->getActiveConfig();
669 }
670 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700671}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700672
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700673void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
674 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
675 this);
676 int32_t type = hw->getDisplayType();
677 int currentMode = hw->getActiveConfig();
678
679 if (mode == currentMode) {
680 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
681 return;
682 }
683
684 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
685 ALOGW("Trying to set config for virtual display");
686 return;
687 }
688
689 hw->setActiveConfig(mode);
690 getHwComposer().setActiveConfig(type, mode);
691}
692
693status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
694 class MessageSetActiveConfig: public MessageBase {
695 SurfaceFlinger& mFlinger;
696 sp<IBinder> mDisplay;
697 int mMode;
698 public:
699 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
700 int mode) :
701 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
702 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700703 Vector<DisplayInfo> configs;
704 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700705 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700706 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700707 mMode, configs.size());
708 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700709 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
710 if (hw == NULL) {
711 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700712 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700713 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
714 ALOGW("Attempt to set active config = %d for virtual display",
715 mMode);
716 } else {
717 mFlinger.setActiveConfigInternal(hw, mMode);
718 }
719 return true;
720 }
721 };
722 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
723 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700724 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700725}
726
Svetoslavd85084b2014-03-20 10:28:31 -0700727status_t SurfaceFlinger::clearAnimationFrameStats() {
728 Mutex::Autolock _l(mStateLock);
729 mAnimFrameTracker.clearStats();
730 return NO_ERROR;
731}
732
733status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
734 Mutex::Autolock _l(mStateLock);
735 mAnimFrameTracker.getStats(outStats);
736 return NO_ERROR;
737}
738
Dan Stozac4f471e2016-03-24 09:31:08 -0700739status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
740 HdrCapabilities* outCapabilities) const {
741 Mutex::Autolock _l(mStateLock);
742
743 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
744 if (displayDevice == nullptr) {
745 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
746 return BAD_VALUE;
747 }
748
749 std::unique_ptr<HdrCapabilities> capabilities =
750 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
751 if (capabilities) {
752 std::swap(*outCapabilities, *capabilities);
753 } else {
754 return BAD_VALUE;
755 }
756
757 return NO_ERROR;
758}
759
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760// ----------------------------------------------------------------------------
761
762sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800763 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700764}
765
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800766// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800767
768void SurfaceFlinger::waitForEvent() {
769 mEventQueue.waitMessage();
770}
771
772void SurfaceFlinger::signalTransaction() {
773 mEventQueue.invalidate();
774}
775
776void SurfaceFlinger::signalLayerUpdate() {
777 mEventQueue.invalidate();
778}
779
780void SurfaceFlinger::signalRefresh() {
781 mEventQueue.refresh();
782}
783
784status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800785 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800786 return mEventQueue.postMessage(msg, reltime);
787}
788
789status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800790 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800791 status_t res = mEventQueue.postMessage(msg, reltime);
792 if (res == NO_ERROR) {
793 msg->wait();
794 }
795 return res;
796}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800797
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700798void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700799 do {
800 waitForEvent();
801 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800802}
803
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700804void SurfaceFlinger::enableHardwareVsync() {
805 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700806 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700807 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700808 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
809 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700810 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700811 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700812}
813
Jesse Hall948fe0c2013-10-14 12:56:09 -0700814void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700815 Mutex::Autolock _l(mHWVsyncLock);
816
Jesse Hall948fe0c2013-10-14 12:56:09 -0700817 if (makeAvailable) {
818 mHWVsyncAvailable = true;
819 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700820 // Hardware vsync is not currently available, so abort the resync
821 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700822 return;
823 }
824
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
826 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700827
828 mPrimaryDispSync.reset();
829 mPrimaryDispSync.setPeriod(period);
830
831 if (!mPrimaryHWVsyncEnabled) {
832 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700833 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
834 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700835 mPrimaryHWVsyncEnabled = true;
836 }
837}
838
Jesse Hall948fe0c2013-10-14 12:56:09 -0700839void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700840 Mutex::Autolock _l(mHWVsyncLock);
841 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700842 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
843 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700844 mPrimaryDispSync.endResync();
845 mPrimaryHWVsyncEnabled = false;
846 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700847 if (makeUnavailable) {
848 mHWVsyncAvailable = false;
849 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700850}
851
Tim Murray4a4e4a22016-04-19 16:29:23 +0000852void SurfaceFlinger::resyncWithRateLimit() {
853 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
854 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700855 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000856 }
857}
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700860 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700861
Jamie Gennisd1700752013-10-14 12:22:52 -0700862 { // Scope for the lock
863 Mutex::Autolock _l(mHWVsyncLock);
864 if (type == 0 && mPrimaryHWVsyncEnabled) {
865 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700866 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700867 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700868
869 if (needsHwVsync) {
870 enableHardwareVsync();
871 } else {
872 disableHardwareVsync(false);
873 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700874}
875
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
877 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
878 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
879 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700880
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 // All non-virtual displays are currently considered secure.
882 bool isSecure = true;
883
884 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
885 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
886 wp<IBinder> token = mBuiltinDisplays[type];
887
888 sp<IGraphicBufferProducer> producer;
889 sp<IGraphicBufferConsumer> consumer;
890 BufferQueue::createBufferQueue(&producer, &consumer,
891 new GraphicBufferAlloc());
892
893 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
894 DisplayDevice::DISPLAY_PRIMARY, consumer);
895 sp<DisplayDevice> hw = new DisplayDevice(this,
896 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
897 producer, mRenderEngine->getEGLConfig());
898 mDisplays.add(token, hw);
899 } else {
900 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700901 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800902 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700904 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800905 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
906 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700907 }
908 setTransactionFlags(eDisplayTransactionNeeded);
909
Andy McFadden9e9689c2012-10-10 18:17:51 -0700910 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700911 }
Mathias Agopian86303202012-07-24 22:46:10 -0700912}
913
Dan Stoza9e56aa02015-11-02 13:00:03 -0800914void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700915 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800916 getHwComposer().setVsyncEnabled(disp,
917 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700918}
919
Mathias Agopian4fec8732012-06-29 14:12:52 -0700920void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800921 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800922 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800923 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -0700924 bool frameMissed = !mHadClientComposition &&
925 mPreviousPresentFence != Fence::NO_FENCE &&
926 mPreviousPresentFence->getSignalTime() == INT64_MAX;
927 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
928 if (frameMissed) {
929 signalLayerUpdate();
930 break;
931 }
932
Dan Stoza6b9454d2014-11-07 16:00:59 -0800933 bool refreshNeeded = handleMessageTransaction();
934 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800935 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800936 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800937 // Signal a refresh if a transaction modified the window state,
938 // a new buffer was latched, or if HWC has requested a full
939 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800940 signalRefresh();
941 }
942 break;
943 }
944 case MessageQueue::REFRESH: {
945 handleMessageRefresh();
946 break;
947 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800948 }
949}
950
Dan Stoza6b9454d2014-11-07 16:00:59 -0800951bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700952 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700953 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700954 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800955 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700956 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800957 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700958}
959
Dan Stoza6b9454d2014-11-07 16:00:59 -0800960bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700961 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800962 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700963}
964
965void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700966 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700967
Pablo Ceballos40845df2016-01-25 17:41:15 -0800968 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700969
Dan Stoza05dacfb2016-07-01 13:33:38 -0700970 preComposition();
971 rebuildLayerStacks();
972 setUpHWComposer();
973 doDebugFlashRegions();
974 doComposition();
975 postComposition(refreshStartTime);
976
977 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
978 mHadClientComposition = mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700979
Dan Stoza9e56aa02015-11-02 13:00:03 -0800980 // Release any buffers which were replaced this frame
981 for (auto& layer : mLayersWithQueuedFrames) {
982 layer->releasePendingBuffer();
983 }
984 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700985}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700986
Mathias Agopiancd60f992012-08-16 16:28:27 -0700987void SurfaceFlinger::doDebugFlashRegions()
988{
989 // is debugging enabled
990 if (CC_LIKELY(!mDebugRegion))
991 return;
992
993 const bool repaintEverything = mRepaintEverything;
994 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
995 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700996 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700997 // transform the dirty region into this screen's coordinate space
998 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
999 if (!dirtyRegion.isEmpty()) {
1000 // redraw the whole screen
1001 doComposeSurfaces(hw, Region(hw->bounds()));
1002
1003 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001004 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001005 RenderEngine& engine(getRenderEngine());
1006 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1007
Mathias Agopianda27af92012-09-13 18:17:13 -07001008 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001009 }
1010 }
1011 }
1012
1013 postFramebuffer();
1014
1015 if (mDebugRegion > 1) {
1016 usleep(mDebugRegion * 1000);
1017 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001018
Dan Stoza9e56aa02015-11-02 13:00:03 -08001019 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001020 auto& displayDevice = mDisplays[displayId];
1021 if (!displayDevice->isDisplayOn()) {
1022 continue;
1023 }
1024
1025 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001026 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1027 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001028 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001029}
1030
1031void SurfaceFlinger::preComposition()
1032{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001033 ATRACE_CALL();
1034 ALOGV("preComposition");
1035
Mathias Agopiancd60f992012-08-16 16:28:27 -07001036 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001037 const LayerVector& layers(mDrawingState.layersSortedByZ);
1038 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001039 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001040 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001041 needExtraInvalidate = true;
1042 }
1043 }
1044 if (needExtraInvalidate) {
1045 signalLayerUpdate();
1046 }
1047}
1048
Pablo Ceballos40845df2016-01-25 17:41:15 -08001049void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001050{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001051 ATRACE_CALL();
1052 ALOGV("postComposition");
1053
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001054 const LayerVector& layers(mDrawingState.layersSortedByZ);
1055 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001056 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001057 bool frameLatched = layers[i]->onPostComposition();
1058 if (frameLatched) {
1059 recordBufferingStats(layers[i]->getName().string(),
1060 layers[i]->getOccupancyHistory(false));
1061 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001062 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001063
Dan Stoza9e56aa02015-11-02 13:00:03 -08001064 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065
1066 if (presentFence->isValid()) {
1067 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1068 enableHardwareVsync();
1069 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001070 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071 }
1072 }
1073
Dan Stozab90cf072015-03-05 11:05:59 -08001074 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001075 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001076 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077 enableHardwareVsync();
1078 }
1079 }
1080
Pablo Ceballos40845df2016-01-25 17:41:15 -08001081 mFenceTracker.addFrame(refreshStartTime, presentFence,
1082 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1083
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001084 if (mAnimCompositionPending) {
1085 mAnimCompositionPending = false;
1086
Jesse Halla9a1b002013-02-27 16:39:25 -08001087 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001088 mAnimFrameTracker.setActualPresentFence(presentFence);
1089 } else {
1090 // The HWC doesn't support present fences, so use the refresh
1091 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001092 nsecs_t presentTime =
1093 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001094 mAnimFrameTracker.setActualPresentTime(presentTime);
1095 }
1096 mAnimFrameTracker.advanceFrame();
1097 }
Dan Stozab90cf072015-03-05 11:05:59 -08001098
1099 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1100 return;
1101 }
1102
1103 nsecs_t currentTime = systemTime();
1104 if (mHasPoweredOff) {
1105 mHasPoweredOff = false;
1106 } else {
1107 nsecs_t period = mPrimaryDispSync.getPeriod();
1108 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1109 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1110 if (numPeriods < NUM_BUCKETS - 1) {
1111 mFrameBuckets[numPeriods] += elapsedTime;
1112 } else {
1113 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1114 }
1115 mTotalTime += elapsedTime;
1116 }
1117 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001118}
1119
1120void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001121 ATRACE_CALL();
1122 ALOGV("rebuildLayerStacks");
1123
Mathias Agopiancd60f992012-08-16 16:28:27 -07001124 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001125 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001126 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001127 mVisibleRegionsDirty = false;
1128 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001129
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001130 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001131 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001132 Region opaqueRegion;
1133 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134 Vector<sp<Layer>> layersSortedByZ;
1135 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1136 const Transform& tr(displayDevice->getTransform());
1137 const Rect bounds(displayDevice->getBounds());
1138 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001139 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140 displayDevice->getLayerStack(), dirtyRegion,
1141 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001142
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001143 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001144 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001145 const sp<Layer>& layer(layers[i]);
1146 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001147 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001148 Region drawRegion(tr.transform(
1149 layer->visibleNonTransparentRegion));
1150 drawRegion.andSelf(bounds);
1151 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001152 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001153 } else {
1154 // Clear out the HWC layer if this layer was
1155 // previously visible, but no longer is
1156 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1157 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001158 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001159 }
1160 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001161 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001162 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1163 displayDevice->undefinedRegion.set(bounds);
1164 displayDevice->undefinedRegion.subtractSelf(
1165 tr.transform(opaqueRegion));
1166 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001167 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001168 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001169}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001170
Mathias Agopiancd60f992012-08-16 16:28:27 -07001171void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001172 ATRACE_CALL();
1173 ALOGV("setUpHWComposer");
1174
Jesse Hall028dc8f2013-08-20 16:35:32 -07001175 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001176 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1177 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1178 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1179
1180 // If nothing has changed (!dirty), don't recompose.
1181 // If something changed, but we don't currently have any visible layers,
1182 // and didn't when we last did a composition, then skip it this time.
1183 // The second rule does two things:
1184 // - When all layers are removed from a display, we'll emit one black
1185 // frame, then nothing more until we get new layers.
1186 // - When a display is created with a private layer stack, we won't
1187 // emit any black frames until a layer is added to the layer stack.
1188 bool mustRecompose = dirty && !(empty && wasEmpty);
1189
1190 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1191 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1192 mustRecompose ? "doing" : "skipping",
1193 dirty ? "+" : "-",
1194 empty ? "+" : "-",
1195 wasEmpty ? "+" : "-");
1196
Dan Stoza71433162014-02-04 16:22:36 -08001197 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001198
1199 if (mustRecompose) {
1200 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1201 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001202 }
1203
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204 // build the h/w work list
1205 if (CC_UNLIKELY(mGeometryInvalid)) {
1206 mGeometryInvalid = false;
1207 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1208 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1209 const auto hwcId = displayDevice->getHwcDisplayId();
1210 if (hwcId >= 0) {
1211 const Vector<sp<Layer>>& currentLayers(
1212 displayDevice->getVisibleLayersSortedByZ());
1213 bool foundLayerWithoutHwc = false;
1214 for (auto& layer : currentLayers) {
1215 if (!layer->hasHwcLayer(hwcId)) {
1216 auto hwcLayer = mHwc->createLayer(hwcId);
1217 if (hwcLayer) {
1218 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1219 } else {
1220 layer->forceClientComposition(hwcId);
1221 foundLayerWithoutHwc = true;
1222 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001223 }
1224 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001225
Dan Stoza9e56aa02015-11-02 13:00:03 -08001226 layer->setGeometry(displayDevice);
1227 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1228 mHasColorMatrix) {
1229 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001230 }
1231 }
1232 }
1233 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234 }
Riley Andrews03414a12014-07-01 14:22:59 -07001235
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 // Set the per-frame data
1237 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1238 auto& displayDevice = mDisplays[displayId];
1239 const auto hwcId = displayDevice->getHwcDisplayId();
1240 if (hwcId < 0) {
1241 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001242 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1244 layer->setPerFrameData(displayDevice);
1245 }
1246 }
1247
1248 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001249 auto& displayDevice = mDisplays[displayId];
1250 if (!displayDevice->isDisplayOn()) {
1251 continue;
1252 }
1253
1254 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001255 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1256 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001257 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001258}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001259
Mathias Agopiancd60f992012-08-16 16:28:27 -07001260void SurfaceFlinger::doComposition() {
1261 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001262 ALOGV("doComposition");
1263
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001264 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001265 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001266 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001267 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001268 // transform the dirty region into this screen's coordinate space
1269 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001270
1271 // repaint the framebuffer (if needed)
1272 doDisplayComposition(hw, dirtyRegion);
1273
Mathias Agopiancd60f992012-08-16 16:28:27 -07001274 hw->dirtyRegion.clear();
1275 hw->flip(hw->swapRegion);
1276 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001277 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001278 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001279 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001280}
1281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001282void SurfaceFlinger::postFramebuffer()
1283{
Mathias Agopian841cde52012-03-01 15:44:37 -08001284 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001285 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001286
Mathias Agopiana44b0412011-10-16 18:46:35 -07001287 const nsecs_t now = systemTime();
1288 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001289
Dan Stoza9e56aa02015-11-02 13:00:03 -08001290 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1291 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001292 if (!displayDevice->isDisplayOn()) {
1293 continue;
1294 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001295 const auto hwcId = displayDevice->getHwcDisplayId();
1296 if (hwcId >= 0) {
1297 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001298 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001299 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 if (displayId == 0) {
1301 // Make the default display current because the VirtualDisplayDevice
1302 // code cannot deal with dequeueBuffer() being called outside of the
1303 // composition loop; however the code below can call glFlush() which
1304 // is allowed to (and does in some case) call dequeueBuffer().
1305 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1306 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1308 sp<Fence> releaseFence = Fence::NO_FENCE;
1309 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1310 releaseFence = displayDevice->getClientTargetAcquireFence();
1311 } else {
1312 auto hwcLayer = layer->getHwcLayer(hwcId);
1313 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001314 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 layer->onLayerDisplayed(releaseFence);
1316 }
1317 if (hwcId >= 0) {
1318 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001319 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001320 }
1321
Mathias Agopiana44b0412011-10-16 18:46:35 -07001322 mLastSwapBufferTime = systemTime() - now;
1323 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001324
1325 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1326 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1327 logFrameStats();
1328 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001329}
1330
Mathias Agopian87baae12012-07-31 12:38:26 -07001331void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332{
Mathias Agopian841cde52012-03-01 15:44:37 -08001333 ATRACE_CALL();
1334
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001335 // here we keep a copy of the drawing state (that is the state that's
1336 // going to be overwritten by handleTransactionLocked()) outside of
1337 // mStateLock so that the side-effects of the State assignment
1338 // don't happen with mStateLock held (which can cause deadlocks).
1339 State drawingState(mDrawingState);
1340
Mathias Agopianca4d3602011-05-19 15:38:14 -07001341 Mutex::Autolock _l(mStateLock);
1342 const nsecs_t now = systemTime();
1343 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344
Mathias Agopianca4d3602011-05-19 15:38:14 -07001345 // Here we're guaranteed that some transaction flags are set
1346 // so we can call handleTransactionLocked() unconditionally.
1347 // We call getTransactionFlags(), which will also clear the flags,
1348 // with mStateLock held to guarantee that mCurrentState won't change
1349 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001350
Mathias Agopiane57f2922012-08-09 16:29:12 -07001351 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001352 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001353
Mathias Agopianca4d3602011-05-19 15:38:14 -07001354 mLastTransactionTime = systemTime() - now;
1355 mDebugInTransaction = 0;
1356 invalidateHwcGeometry();
1357 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001358}
1359
Mathias Agopian87baae12012-07-31 12:38:26 -07001360void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001361{
1362 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001363 const size_t count = currentLayers.size();
1364
Dan Stoza7dde5992015-05-22 09:51:44 -07001365 // Notify all layers of available frames
1366 for (size_t i = 0; i < count; ++i) {
1367 currentLayers[i]->notifyAvailableFrames();
1368 }
1369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370 /*
1371 * Traversal of the children
1372 * (perform the transaction for each of them if needed)
1373 */
1374
Mathias Agopian3559b072012-08-15 13:46:03 -07001375 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001376 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001377 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001378 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1379 if (!trFlags) continue;
1380
1381 const uint32_t flags = layer->doTransaction(0);
1382 if (flags & Layer::eVisibleRegion)
1383 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384 }
1385 }
1386
1387 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001388 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001389 */
1390
Mathias Agopiane57f2922012-08-09 16:29:12 -07001391 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001392 // here we take advantage of Vector's copy-on-write semantics to
1393 // improve performance by skipping the transaction entirely when
1394 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001395 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1396 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001397 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001398 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001399 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001400 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001401
1402 // find the displays that were removed
1403 // (ie: in drawing state but not in current state)
1404 // also handle displays that changed
1405 // (ie: displays that are in both lists)
1406 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001407 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1408 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001409 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001410 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001411 // Call makeCurrent() on the primary display so we can
1412 // be sure that nothing associated with this display
1413 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001414 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001415 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001416 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1417 if (hw != NULL)
1418 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001419 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001420 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001421 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001422 } else {
1423 ALOGW("trying to remove the main display");
1424 }
1425 } else {
1426 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001427 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001428 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001429 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1430 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001431 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001432 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001433 // recreating the DisplayDevice, so we just remove it
1434 // from the drawing state, so that it get re-added
1435 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001436 sp<DisplayDevice> hw(getDisplayDevice(display));
1437 if (hw != NULL)
1438 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001439 mDisplays.removeItem(display);
1440 mDrawingState.displays.removeItemsAt(i);
1441 dc--; i--;
1442 // at this point we must loop to the next item
1443 continue;
1444 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001445
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001446 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001447 if (disp != NULL) {
1448 if (state.layerStack != draw[i].layerStack) {
1449 disp->setLayerStack(state.layerStack);
1450 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001451 if ((state.orientation != draw[i].orientation)
1452 || (state.viewport != draw[i].viewport)
1453 || (state.frame != draw[i].frame))
1454 {
1455 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001456 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001457 }
Michael Lentine47e45402014-07-18 15:34:25 -07001458 if (state.width != draw[i].width || state.height != draw[i].height) {
1459 disp->setDisplaySize(state.width, state.height);
1460 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001461 }
1462 }
1463 }
1464
1465 // find displays that were added
1466 // (ie: in current state but not in drawing state)
1467 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001468 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001469 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001470
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001471 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001472 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001473 sp<IGraphicBufferProducer> bqProducer;
1474 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001475 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1476 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001477
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001479 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001480 // Virtual displays without a surface are dormant:
1481 // they have external state (layer stack, projection,
1482 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001483 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001484
Dan Stoza1f3efb12014-10-15 16:34:55 -07001485 int width = 0;
1486 int status = state.surface->query(
1487 NATIVE_WINDOW_WIDTH, &width);
1488 ALOGE_IF(status != NO_ERROR,
1489 "Unable to query width (%d)", status);
1490 int height = 0;
1491 status = state.surface->query(
1492 NATIVE_WINDOW_HEIGHT, &height);
1493 ALOGE_IF(status != NO_ERROR,
1494 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001495 int intFormat = 0;
1496 status = state.surface->query(
1497 NATIVE_WINDOW_FORMAT, &intFormat);
1498 ALOGE_IF(status != NO_ERROR,
1499 "Unable to query format (%d)", status);
1500 auto format = static_cast<android_pixel_format_t>(
1501 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001502
Dan Stoza5cf424b2016-05-20 14:02:39 -07001503 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001504 &hwcId);
1505
Dan Stoza5cf424b2016-05-20 14:02:39 -07001506 // TODO: Plumb requested format back up to consumer
1507
Dan Stoza9e56aa02015-11-02 13:00:03 -08001508 sp<VirtualDisplaySurface> vds =
1509 new VirtualDisplaySurface(*mHwc,
1510 hwcId, state.surface, bqProducer,
1511 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001512
1513 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001514 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001515 }
1516 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001517 ALOGE_IF(state.surface!=NULL,
1518 "adding a supported display, but rendering "
1519 "surface is provided (%p), ignoring it",
1520 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001521 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1522 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1523 dispSurface = new FramebufferSurface(*mHwc,
1524 DisplayDevice::DISPLAY_EXTERNAL,
1525 bqConsumer);
1526 producer = bqProducer;
1527 } else {
1528 ALOGE("Attempted to add non-external non-virtual"
1529 " display");
1530 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001531 }
1532
1533 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001534 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001535 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 state.type, hwcId, state.isSecure, display,
1537 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001538 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001539 hw->setLayerStack(state.layerStack);
1540 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001541 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001542 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001543 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001545 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001546 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001547 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001548 }
1549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001550 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001552
Mathias Agopian84300952012-11-21 16:02:13 -08001553 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1554 // The transform hint might have changed for some layers
1555 // (either because a display has changed, or because a layer
1556 // as changed).
1557 //
1558 // Walk through all the layers in currentLayers,
1559 // and update their transform hint.
1560 //
1561 // If a layer is visible only on a single display, then that
1562 // display is used to calculate the hint, otherwise we use the
1563 // default display.
1564 //
1565 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1566 // the hint is set before we acquire a buffer from the surface texture.
1567 //
1568 // NOTE: layer transactions have taken place already, so we use their
1569 // drawing state. However, SurfaceFlinger's own transaction has not
1570 // happened yet, so we must use the current state layer list
1571 // (soon to become the drawing state list).
1572 //
1573 sp<const DisplayDevice> disp;
1574 uint32_t currentlayerStack = 0;
1575 for (size_t i=0; i<count; i++) {
1576 // NOTE: we rely on the fact that layers are sorted by
1577 // layerStack first (so we don't have to traverse the list
1578 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001579 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001580 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001581 if (i==0 || currentlayerStack != layerStack) {
1582 currentlayerStack = layerStack;
1583 // figure out if this layerstack is mirrored
1584 // (more than one display) if so, pick the default display,
1585 // if not, pick the only display it's on.
1586 disp.clear();
1587 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1588 sp<const DisplayDevice> hw(mDisplays[dpy]);
1589 if (hw->getLayerStack() == currentlayerStack) {
1590 if (disp == NULL) {
1591 disp = hw;
1592 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001593 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001594 break;
1595 }
1596 }
1597 }
1598 }
Chet Haase91d25932013-04-11 15:24:55 -07001599 if (disp == NULL) {
1600 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1601 // redraw after transform hint changes. See bug 8508397.
1602
1603 // could be null when this layer is using a layerStack
1604 // that is not visible on any display. Also can occur at
1605 // screen off/on times.
1606 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001607 }
Chet Haase91d25932013-04-11 15:24:55 -07001608 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001609 }
1610 }
1611
1612
Mathias Agopian3559b072012-08-15 13:46:03 -07001613 /*
1614 * Perform our own transaction if needed
1615 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001616
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001617 const LayerVector& layers(mDrawingState.layersSortedByZ);
1618 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001619 // layers have been added
1620 mVisibleRegionsDirty = true;
1621 }
1622
1623 // some layers might have been removed, so
1624 // we need to update the regions they're exposing.
1625 if (mLayersRemoved) {
1626 mLayersRemoved = false;
1627 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001628 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001629 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001630 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001631 if (currentLayers.indexOf(layer) < 0) {
1632 // this layer is not visible anymore
1633 // TODO: we could traverse the tree from front to back and
1634 // compute the actual visible region
1635 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001636 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001637 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001638 Region(Rect(s.active.w, s.active.h)));
1639 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001640 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001642 }
1643
1644 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001645
1646 updateCursorAsync();
1647}
1648
1649void SurfaceFlinger::updateCursorAsync()
1650{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001651 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1652 auto& displayDevice = mDisplays[displayId];
1653 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001654 continue;
1655 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001656
1657 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1658 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001659 }
1660 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661}
1662
1663void SurfaceFlinger::commitTransaction()
1664{
1665 if (!mLayersPendingRemoval.isEmpty()) {
1666 // Notify removed layers now that they can't be drawn from
1667 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001668 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1669 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001670 mLayersPendingRemoval[i]->onRemoved();
1671 }
1672 mLayersPendingRemoval.clear();
1673 }
1674
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001675 // If this transaction is part of a window animation then the next frame
1676 // we composite should be considered an animation as well.
1677 mAnimCompositionPending = mAnimTransactionPending;
1678
Mathias Agopian4fec8732012-06-29 14:12:52 -07001679 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001680 mTransactionPending = false;
1681 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001683}
1684
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001685void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001686 const LayerVector& currentLayers, uint32_t layerStack,
1687 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001688{
Mathias Agopian841cde52012-03-01 15:44:37 -08001689 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001691
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001692 Region aboveOpaqueLayers;
1693 Region aboveCoveredLayers;
1694 Region dirty;
1695
Mathias Agopian87baae12012-07-31 12:38:26 -07001696 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001697
1698 size_t i = currentLayers.size();
1699 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001700 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001701
1702 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001703 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001704
Jesse Hall01e29052013-02-19 16:13:35 -08001705 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001706 if (s.layerStack != layerStack)
1707 continue;
1708
Mathias Agopianab028732010-03-16 16:41:46 -07001709 /*
1710 * opaqueRegion: area of a surface that is fully opaque.
1711 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001712 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001713
1714 /*
1715 * visibleRegion: area of a surface that is visible on screen
1716 * and not fully transparent. This is essentially the layer's
1717 * footprint minus the opaque regions above it.
1718 * Areas covered by a translucent surface are considered visible.
1719 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001720 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001721
1722 /*
1723 * coveredRegion: area of a surface that is covered by all
1724 * visible regions above it (which includes the translucent areas).
1725 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001726 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001727
Jesse Halla8026d22012-09-25 13:25:04 -07001728 /*
1729 * transparentRegion: area of a surface that is hinted to be completely
1730 * transparent. This is only used to tell when the layer has no visible
1731 * non-transparent regions and can be removed from the layer list. It
1732 * does not affect the visibleRegion of this layer or any layers
1733 * beneath it. The hint may not be correct if apps don't respect the
1734 * SurfaceView restrictions (which, sadly, some don't).
1735 */
1736 Region transparentRegion;
1737
Mathias Agopianab028732010-03-16 16:41:46 -07001738
1739 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001740 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001741 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001742 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001743 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001744 if (!visibleRegion.isEmpty()) {
1745 // Remove the transparent area from the visible region
1746 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001747 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001748 if (tr.preserveRects()) {
1749 // transform the transparent region
1750 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001751 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001752 // transformation too complex, can't do the
1753 // transparent region optimization.
1754 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001755 }
Mathias Agopianab028732010-03-16 16:41:46 -07001756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001757
Mathias Agopianab028732010-03-16 16:41:46 -07001758 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001759 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001761 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1762 // the opaque region is the layer's footprint
1763 opaqueRegion = visibleRegion;
1764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765 }
1766 }
1767
Mathias Agopianab028732010-03-16 16:41:46 -07001768 // Clip the covered region to the visible region
1769 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1770
1771 // Update aboveCoveredLayers for next (lower) layer
1772 aboveCoveredLayers.orSelf(visibleRegion);
1773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001774 // subtract the opaque region covered by the layers above us
1775 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001776
1777 // compute this layer's dirty region
1778 if (layer->contentDirty) {
1779 // we need to invalidate the whole region
1780 dirty = visibleRegion;
1781 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001782 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001783 layer->contentDirty = false;
1784 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001785 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001786 * the exposed region consists of two components:
1787 * 1) what's VISIBLE now and was COVERED before
1788 * 2) what's EXPOSED now less what was EXPOSED before
1789 *
1790 * note that (1) is conservative, we start with the whole
1791 * visible region but only keep what used to be covered by
1792 * something -- which mean it may have been exposed.
1793 *
1794 * (2) handles areas that were not covered by anything but got
1795 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001796 */
Mathias Agopianab028732010-03-16 16:41:46 -07001797 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001798 const Region oldVisibleRegion = layer->visibleRegion;
1799 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001800 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1801 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802 }
1803 dirty.subtractSelf(aboveOpaqueLayers);
1804
1805 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001806 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807
Mathias Agopianab028732010-03-16 16:41:46 -07001808 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001809 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001810
Jesse Halla8026d22012-09-25 13:25:04 -07001811 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812 layer->setVisibleRegion(visibleRegion);
1813 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001814 layer->setVisibleNonTransparentRegion(
1815 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001816 }
1817
Mathias Agopian87baae12012-07-31 12:38:26 -07001818 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819}
1820
Mathias Agopian87baae12012-07-31 12:38:26 -07001821void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1822 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001823 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001824 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1825 if (hw->getLayerStack() == layerStack) {
1826 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001827 }
1828 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001829}
1830
Dan Stoza6b9454d2014-11-07 16:00:59 -08001831bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001832{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 ALOGV("handlePageFlip");
1834
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001836
Mathias Agopian4fec8732012-06-29 14:12:52 -07001837 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001838 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001840
1841 // Store the set of layers that need updates. This set must not change as
1842 // buffers are being latched, as this could result in a deadlock.
1843 // Example: Two producers share the same command stream and:
1844 // 1.) Layer 0 is latched
1845 // 2.) Layer 0 gets a new frame
1846 // 2.) Layer 1 gets a new frame
1847 // 3.) Layer 1 is latched.
1848 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1849 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001850 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001851 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001852 if (layer->hasQueuedFrame()) {
1853 frameQueued = true;
1854 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001856 } else {
1857 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001858 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001859 } else {
1860 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001861 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001862 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001864 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001865 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001866 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001867 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001868 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001869
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001870 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001871
1872 // If we will need to wake up at some time in the future to deal with a
1873 // queued frame that shouldn't be displayed during this vsync period, wake
1874 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001876 signalLayerUpdate();
1877 }
1878
1879 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001881}
1882
Mathias Agopianad456f92011-01-13 17:53:01 -08001883void SurfaceFlinger::invalidateHwcGeometry()
1884{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001886}
1887
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001888
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001890 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891{
Dan Stoza71433162014-02-04 16:22:36 -08001892 // We only need to actually compose the display if:
1893 // 1) It is being handled by hardware composer, which may need this to
1894 // keep its virtual display state machine in sync, or
1895 // 2) There is work to be done (the dirty region isn't empty)
1896 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1897 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001899 return;
1900 }
1901
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 ALOGV("doDisplayComposition");
1903
Mathias Agopian87baae12012-07-31 12:38:26 -07001904 Region dirtyRegion(inDirtyRegion);
1905
Mathias Agopianb8a55602009-06-26 19:06:36 -07001906 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001907 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908
Mathias Agopian42977342012-08-05 00:40:46 -07001909 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001910 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001911 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1912 // takes a rectangle, we must make sure to update that whole
1913 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001914 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001915 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001916 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001917 // We need to redraw the rectangle that will be updated
1918 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001919 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001920 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001921 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001922 } else {
1923 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001924 dirtyRegion.set(hw->bounds());
1925 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926 }
1927 }
1928
Alan Viverette9c5a3332013-09-12 20:04:35 -07001929 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001930 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001931 } else {
1932 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001933 mat4 colorMatrix = mColorMatrix;
1934 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001935 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001936 }
Dan Stozaf0087992014-10-20 15:46:09 -07001937 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001938 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001939 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001940 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001941
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001942 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001943 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001944
1945 // swap buffers (presentation)
1946 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947}
1948
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949bool SurfaceFlinger::doComposeSurfaces(
1950 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001951{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001953
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 const auto hwcId = displayDevice->getHwcDisplayId();
1955 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1956 if (hasClientComposition) {
1957 ALOGV("hasClientComposition");
1958
1959 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001960 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001962 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1963 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1964 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1965 }
1966 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001967 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001968
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001969 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1971 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001972 // when using overlays, we assume a fully transparent framebuffer
1973 // NOTE: we could reduce how much we need to clear, for instance
1974 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001975 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001976 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001978 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001979 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001981
1982 // we remove the scissor part
1983 // we're left with the letterbox region
1984 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001986
1987 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001989
1990 // but limit it to the dirty region
1991 region.andSelf(dirty);
1992
Mathias Agopianb9494d52012-04-18 02:28:45 -07001993 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001994 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001995 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001997 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001998 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001999
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002001 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002002 // scissor on the main display. It should never be needed
2003 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 const Rect& bounds(displayDevice->getBounds());
2005 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002006 if (scissor != bounds) {
2007 // scissor doesn't match the screen's dimensions, so we
2008 // need to clear everything outside of it and enable
2009 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002010
Mathias Agopianf45c5102012-10-24 16:29:17 -07002011 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 const uint32_t height = displayDevice->getHeight();
2013 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002014 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002015 }
2016 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002017 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002018
Mathias Agopian85d751c2012-08-29 16:59:24 -07002019 /*
2020 * and then, render the layers targeted at the framebuffer
2021 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 ALOGV("Rendering client layers");
2024 const Transform& displayTransform = displayDevice->getTransform();
2025 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002026 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 bool firstLayer = true;
2028 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2029 const Region clip(dirty.intersect(
2030 displayTransform.transform(layer->visibleRegion)));
2031 ALOGV("Layer: %s", layer->getName().string());
2032 ALOGV(" Composition type: %s",
2033 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002034 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 switch (layer->getCompositionType(hwcId)) {
2036 case HWC2::Composition::Cursor:
2037 case HWC2::Composition::Device:
2038 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002039 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2041 layer->isOpaque(state) && (state.alpha == 1.0f)
2042 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002043 // never clear the very first layer since we're
2044 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002047 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 case HWC2::Composition::Client: {
2050 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002051 break;
2052 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002054 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002055 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 } else {
2057 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002058 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002060 }
2061 } else {
2062 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002064 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002066 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002068 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002069 }
2070 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002071
2072 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002074 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002075}
2076
Mathias Agopian3f844832013-08-07 21:24:32 -07002077void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002078 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002079 RenderEngine& engine(getRenderEngine());
2080 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081}
2082
Dan Stoza7d89d062015-04-30 13:29:25 -07002083status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002084 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002085 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002086 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002087{
Dan Stoza7d89d062015-04-30 13:29:25 -07002088 // add this layer to the current state list
2089 {
2090 Mutex::Autolock _l(mStateLock);
2091 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2092 return NO_MEMORY;
2093 }
2094 mCurrentState.layersSortedByZ.add(lbc);
2095 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2096 }
2097
Mathias Agopian96f08192010-06-02 23:28:45 -07002098 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002099 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002100
Dan Stoza7d89d062015-04-30 13:29:25 -07002101 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002102}
2103
Mathias Agopian3f844832013-08-07 21:24:32 -07002104status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002106 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002107 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002108 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002109 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002110 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111 return NO_ERROR;
2112 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002113 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114}
2115
Dan Stozac7014012014-02-14 15:03:43 -08002116uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002117 return android_atomic_release_load(&mTransactionFlags);
2118}
2119
Mathias Agopian3f844832013-08-07 21:24:32 -07002120uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2122}
2123
Mathias Agopian3f844832013-08-07 21:24:32 -07002124uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002125 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2126 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002127 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 }
2129 return old;
2130}
2131
Mathias Agopian8b33f032012-07-24 20:43:54 -07002132void SurfaceFlinger::setTransactionState(
2133 const Vector<ComposerState>& state,
2134 const Vector<DisplayState>& displays,
2135 uint32_t flags)
2136{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002137 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002138 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002139 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002140
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002141 if (flags & eAnimation) {
2142 // For window updates that are part of an animation we must wait for
2143 // previous animation "frames" to be handled.
2144 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002145 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002146 if (CC_UNLIKELY(err != NO_ERROR)) {
2147 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002148 // caller after a few seconds.
2149 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2150 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002151 mAnimTransactionPending = false;
2152 break;
2153 }
2154 }
2155 }
2156
Mathias Agopiane57f2922012-08-09 16:29:12 -07002157 size_t count = displays.size();
2158 for (size_t i=0 ; i<count ; i++) {
2159 const DisplayState& s(displays[i]);
2160 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002161 }
2162
Mathias Agopiane57f2922012-08-09 16:29:12 -07002163 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002164 for (size_t i=0 ; i<count ; i++) {
2165 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002166 // Here we need to check that the interface we're given is indeed
2167 // one of our own. A malicious client could give us a NULL
2168 // IInterface, or one of its own or even one of our own but a
2169 // different type. All these situations would cause us to crash.
2170 //
2171 // NOTE: it would be better to use RTTI as we could directly check
2172 // that we have a Client*. however, RTTI is disabled in Android.
2173 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002174 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002175 if (binder != NULL) {
2176 String16 desc(binder->getInterfaceDescriptor());
2177 if (desc == ISurfaceComposerClient::descriptor) {
2178 sp<Client> client( static_cast<Client *>(s.client.get()) );
2179 transactionFlags |= setClientStateLocked(client, s.state);
2180 }
2181 }
2182 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002183 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002184
Robert Carr2a7dbb42016-05-24 11:41:28 -07002185 // If a synchronous transaction is explicitly requested without any changes,
2186 // force a transaction anyway. This can be used as a flush mechanism for
2187 // previous async transactions.
2188 if (transactionFlags == 0 && (flags & eSynchronous)) {
2189 transactionFlags = eTransactionNeeded;
2190 }
2191
Mathias Agopian386aa982011-11-07 21:58:03 -08002192 if (transactionFlags) {
2193 // this triggers the transaction
2194 setTransactionFlags(transactionFlags);
2195
2196 // if this is a synchronous transaction, wait for it to take effect
2197 // before returning.
2198 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002199 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002200 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002201 if (flags & eAnimation) {
2202 mAnimTransactionPending = true;
2203 }
2204 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002205 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2206 if (CC_UNLIKELY(err != NO_ERROR)) {
2207 // just in case something goes wrong in SF, return to the
2208 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002209 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2210 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002211 break;
2212 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002213 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214 }
2215}
2216
Mathias Agopiane57f2922012-08-09 16:29:12 -07002217uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2218{
Jesse Hall9a143922012-10-04 16:29:19 -07002219 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2220 if (dpyIdx < 0)
2221 return 0;
2222
Mathias Agopiane57f2922012-08-09 16:29:12 -07002223 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002224 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002225 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002226 const uint32_t what = s.what;
2227 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002228 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002229 disp.surface = s.surface;
2230 flags |= eDisplayTransactionNeeded;
2231 }
2232 }
2233 if (what & DisplayState::eLayerStackChanged) {
2234 if (disp.layerStack != s.layerStack) {
2235 disp.layerStack = s.layerStack;
2236 flags |= eDisplayTransactionNeeded;
2237 }
2238 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002239 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002240 if (disp.orientation != s.orientation) {
2241 disp.orientation = s.orientation;
2242 flags |= eDisplayTransactionNeeded;
2243 }
2244 if (disp.frame != s.frame) {
2245 disp.frame = s.frame;
2246 flags |= eDisplayTransactionNeeded;
2247 }
2248 if (disp.viewport != s.viewport) {
2249 disp.viewport = s.viewport;
2250 flags |= eDisplayTransactionNeeded;
2251 }
2252 }
Michael Lentine47e45402014-07-18 15:34:25 -07002253 if (what & DisplayState::eDisplaySizeChanged) {
2254 if (disp.width != s.width) {
2255 disp.width = s.width;
2256 flags |= eDisplayTransactionNeeded;
2257 }
2258 if (disp.height != s.height) {
2259 disp.height = s.height;
2260 flags |= eDisplayTransactionNeeded;
2261 }
2262 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002263 }
2264 return flags;
2265}
2266
2267uint32_t SurfaceFlinger::setClientStateLocked(
2268 const sp<Client>& client,
2269 const layer_state_t& s)
2270{
2271 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002272 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002273 if (layer != 0) {
2274 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002275 bool geometryAppliesWithResize =
2276 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002277 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002278 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002279 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002280 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002281 }
2282 if (what & layer_state_t::eLayerChanged) {
2283 // NOTE: index needs to be calculated before we update the state
2284 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002285 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002286 mCurrentState.layersSortedByZ.removeAt(idx);
2287 mCurrentState.layersSortedByZ.add(layer);
2288 // we need traversal (state changed)
2289 // AND transaction (list changed)
2290 flags |= eTransactionNeeded|eTraversalNeeded;
2291 }
2292 }
2293 if (what & layer_state_t::eSizeChanged) {
2294 if (layer->setSize(s.w, s.h)) {
2295 flags |= eTraversalNeeded;
2296 }
2297 }
2298 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002300 flags |= eTraversalNeeded;
2301 }
2302 if (what & layer_state_t::eMatrixChanged) {
2303 if (layer->setMatrix(s.matrix))
2304 flags |= eTraversalNeeded;
2305 }
2306 if (what & layer_state_t::eTransparentRegionChanged) {
2307 if (layer->setTransparentRegionHint(s.transparentRegion))
2308 flags |= eTraversalNeeded;
2309 }
Dan Stoza23116082015-06-18 14:58:39 -07002310 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002311 if (layer->setFlags(s.flags, s.mask))
2312 flags |= eTraversalNeeded;
2313 }
2314 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002315 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002316 flags |= eTraversalNeeded;
2317 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002318 if (what & layer_state_t::eFinalCropChanged) {
2319 if (layer->setFinalCrop(s.finalCrop))
2320 flags |= eTraversalNeeded;
2321 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002322 if (what & layer_state_t::eLayerStackChanged) {
2323 // NOTE: index needs to be calculated before we update the state
2324 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002325 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002326 mCurrentState.layersSortedByZ.removeAt(idx);
2327 mCurrentState.layersSortedByZ.add(layer);
2328 // we need traversal (state changed)
2329 // AND transaction (list changed)
2330 flags |= eTransactionNeeded|eTraversalNeeded;
2331 }
2332 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002333 if (what & layer_state_t::eDeferTransaction) {
2334 layer->deferTransactionUntil(s.handle, s.frameNumber);
2335 // We don't trigger a traversal here because if no other state is
2336 // changed, we don't want this to cause any more work
2337 }
Robert Carrc3574f72016-03-24 12:19:32 -07002338 if (what & layer_state_t::eOverrideScalingModeChanged) {
2339 layer->setOverrideScalingMode(s.overrideScalingMode);
2340 // We don't trigger a traversal here because if no other state is
2341 // changed, we don't want this to cause any more work
2342 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002343 }
2344 return flags;
2345}
2346
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002347status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002348 const String8& name,
2349 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002350 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2351 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002353 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002354 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002355 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002356 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002357 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002358 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002359
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002360 status_t result = NO_ERROR;
2361
2362 sp<Layer> layer;
2363
Mathias Agopian3165cc22012-08-08 19:42:09 -07002364 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2365 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002366 result = createNormalLayer(client,
2367 name, w, h, flags, format,
2368 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002370 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002371 result = createDimLayer(client,
2372 name, w, h, flags,
2373 handle, gbp, &layer);
2374 break;
2375 default:
2376 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377 break;
2378 }
2379
Dan Stoza7d89d062015-04-30 13:29:25 -07002380 if (result != NO_ERROR) {
2381 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002383
2384 result = addClientLayer(client, *handle, *gbp, layer);
2385 if (result != NO_ERROR) {
2386 return result;
2387 }
2388
2389 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002390 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391}
2392
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002393status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2394 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2395 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396{
2397 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002398 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399 case PIXEL_FORMAT_TRANSPARENT:
2400 case PIXEL_FORMAT_TRANSLUCENT:
2401 format = PIXEL_FORMAT_RGBA_8888;
2402 break;
2403 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002404 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405 break;
2406 }
2407
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002408 *outLayer = new Layer(this, client, name, w, h, flags);
2409 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2410 if (err == NO_ERROR) {
2411 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002412 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002414
2415 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2416 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417}
2418
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002419status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2420 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2421 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002423 *outLayer = new LayerDim(this, client, name, w, h, flags);
2424 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002425 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002426 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002427}
2428
Mathias Agopianac9fa422013-02-11 16:40:36 -08002429status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430{
Mathias Agopian67106042013-03-14 19:18:13 -07002431 // called by the window manager when it wants to remove a Layer
2432 status_t err = NO_ERROR;
2433 sp<Layer> l(client->getLayerUser(handle));
2434 if (l != NULL) {
2435 err = removeLayer(l);
2436 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2437 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002438 }
2439 return err;
2440}
2441
Mathias Agopian13127d82013-03-05 17:47:11 -08002442status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002443{
Mathias Agopian67106042013-03-14 19:18:13 -07002444 // called by ~LayerCleaner() when all references to the IBinder (handle)
2445 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002446 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002447 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002448 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002449 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002450 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002451 "error removing layer=%p (%s)", l.get(), strerror(-err));
2452 }
2453 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454}
2455
Mathias Agopianb60314a2012-04-10 22:09:54 -07002456// ---------------------------------------------------------------------------
2457
Andy McFadden13a082e2012-08-24 10:16:42 -07002458void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002459 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002460 Vector<ComposerState> state;
2461 Vector<DisplayState> displays;
2462 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002463 d.what = DisplayState::eDisplayProjectionChanged |
2464 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002465 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002466 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002467 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002468 d.frame.makeInvalid();
2469 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002470 d.width = 0;
2471 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002472 displays.add(d);
2473 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002474 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002475
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2477 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002478 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002479}
2480
2481void SurfaceFlinger::initializeDisplays() {
2482 class MessageScreenInitialized : public MessageBase {
2483 SurfaceFlinger* flinger;
2484 public:
2485 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2486 virtual bool handler() {
2487 flinger->onInitializeDisplays();
2488 return true;
2489 }
2490 };
2491 sp<MessageBase> msg = new MessageScreenInitialized(this);
2492 postMessageAsync(msg); // we may be called from main thread, use async message
2493}
2494
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002495void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2496 int mode) {
2497 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2498 this);
2499 int32_t type = hw->getDisplayType();
2500 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002501
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002502 if (mode == currentMode) {
2503 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002504 return;
2505 }
2506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002507 hw->setPowerMode(mode);
2508 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2509 ALOGW("Trying to set power mode for virtual display");
2510 return;
2511 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002512
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002513 if (currentMode == HWC_POWER_MODE_OFF) {
2514 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002515 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2516 // FIXME: eventthread only knows about the main display right now
2517 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002518 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002521 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002522 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002523 repaintEverything();
2524 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002525 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002526 disableHardwareVsync(true); // also cancels any in-progress resync
2527
Mathias Agopiancde87a32012-09-13 14:09:01 -07002528 // FIXME: eventthread only knows about the main display right now
2529 mEventThread->onScreenReleased();
2530 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002531
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002532 getHwComposer().setPowerMode(type, mode);
2533 mVisibleRegionsDirty = true;
2534 // from this point on, SF will stop drawing on this display
2535 } else {
2536 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002537 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002538}
2539
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002540void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2541 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002542 SurfaceFlinger& mFlinger;
2543 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002544 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002545 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002546 MessageSetPowerMode(SurfaceFlinger& flinger,
2547 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2548 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002549 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002550 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002551 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002552 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002553 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002554 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002555 ALOGW("Attempt to set power mode = %d for virtual display",
2556 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002557 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002558 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002559 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002560 return true;
2561 }
2562 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002563 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002564 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002565}
2566
2567// ---------------------------------------------------------------------------
2568
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2570{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002572
Mathias Agopianbd115332013-04-18 16:41:04 -07002573 IPCThreadState* ipc = IPCThreadState::self();
2574 const int pid = ipc->getCallingPid();
2575 const int uid = ipc->getCallingUid();
2576 if ((uid != AID_SHELL) &&
2577 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002578 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002579 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002581 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002582 // (this would indicate SF is stuck, but we want to be able to
2583 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002584 status_t err = mStateLock.timedLock(s2ns(1));
2585 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002586 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002587 result.appendFormat(
2588 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2589 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002590 }
2591
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002592 bool dumpAll = true;
2593 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002594 size_t numArgs = args.size();
2595 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002596 if ((index < numArgs) &&
2597 (args[index] == String16("--list"))) {
2598 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002599 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002600 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002601 }
2602
2603 if ((index < numArgs) &&
2604 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002605 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002606 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002607 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002608 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002609
2610 if ((index < numArgs) &&
2611 (args[index] == String16("--latency-clear"))) {
2612 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002613 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002614 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002615 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002616
2617 if ((index < numArgs) &&
2618 (args[index] == String16("--dispsync"))) {
2619 index++;
2620 mPrimaryDispSync.dump(result);
2621 dumpAll = false;
2622 }
Dan Stozab90cf072015-03-05 11:05:59 -08002623
2624 if ((index < numArgs) &&
2625 (args[index] == String16("--static-screen"))) {
2626 index++;
2627 dumpStaticScreenStats(result);
2628 dumpAll = false;
2629 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002630
2631 if ((index < numArgs) &&
2632 (args[index] == String16("--fences"))) {
2633 index++;
2634 mFenceTracker.dump(&result);
2635 dumpAll = false;
2636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002638
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002639 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002640 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002641 }
2642
Mathias Agopian9795c422009-08-26 16:36:26 -07002643 if (locked) {
2644 mStateLock.unlock();
2645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 }
2647 write(fd, result.string(), result.size());
2648 return NO_ERROR;
2649}
2650
Dan Stozac7014012014-02-14 15:03:43 -08002651void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2652 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002653{
2654 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2655 const size_t count = currentLayers.size();
2656 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002657 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002658 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002659 }
2660}
2661
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002662void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002663 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002664{
2665 String8 name;
2666 if (index < args.size()) {
2667 name = String8(args[index]);
2668 index++;
2669 }
2670
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2672 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002673 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002674
2675 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002676 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002677 } else {
2678 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2679 const size_t count = currentLayers.size();
2680 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002681 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002682 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002683 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002684 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002685 }
2686 }
2687}
2688
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002689void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002690 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002691{
2692 String8 name;
2693 if (index < args.size()) {
2694 name = String8(args[index]);
2695 index++;
2696 }
2697
2698 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2699 const size_t count = currentLayers.size();
2700 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002701 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002702 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002703 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002704 }
2705 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002706
Svetoslavd85084b2014-03-20 10:28:31 -07002707 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002708}
2709
Jamie Gennis6547ff42013-07-16 20:12:42 -07002710// This should only be called from the main thread. Otherwise it would need
2711// the lock and should use mCurrentState rather than mDrawingState.
2712void SurfaceFlinger::logFrameStats() {
2713 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2714 const size_t count = drawingLayers.size();
2715 for (size_t i=0 ; i<count ; i++) {
2716 const sp<Layer>& layer(drawingLayers[i]);
2717 layer->logFrameStats();
2718 }
2719
2720 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2721}
2722
Andy McFadden4803b742012-09-24 19:07:20 -07002723/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2724{
2725 static const char* config =
2726 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002727#ifdef HAS_CONTEXT_PRIORITY
2728 " HAS_CONTEXT_PRIORITY"
2729#endif
2730#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2731 " NEVER_DEFAULT_TO_ASYNC_MODE"
2732#endif
2733#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2734 " TARGET_DISABLE_TRIPLE_BUFFERING"
2735#endif
2736 "]";
2737 result.append(config);
2738}
2739
Dan Stozab90cf072015-03-05 11:05:59 -08002740void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2741{
2742 result.appendFormat("Static screen stats:\n");
2743 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2744 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2745 float percent = 100.0f *
2746 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2747 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2748 b + 1, bucketTimeSec, percent);
2749 }
2750 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2751 float percent = 100.0f *
2752 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2753 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2754 NUM_BUCKETS - 1, bucketTimeSec, percent);
2755}
2756
Dan Stozae77c7662016-05-13 11:37:28 -07002757void SurfaceFlinger::recordBufferingStats(const char* layerName,
2758 std::vector<OccupancyTracker::Segment>&& history) {
2759 Mutex::Autolock lock(mBufferingStatsMutex);
2760 auto& stats = mBufferingStats[layerName];
2761 for (const auto& segment : history) {
2762 if (!segment.usedThirdBuffer) {
2763 stats.twoBufferTime += segment.totalTime;
2764 }
2765 if (segment.occupancyAverage < 1.0f) {
2766 stats.doubleBufferedTime += segment.totalTime;
2767 } else if (segment.occupancyAverage < 2.0f) {
2768 stats.tripleBufferedTime += segment.totalTime;
2769 }
2770 ++stats.numSegments;
2771 stats.totalTime += segment.totalTime;
2772 }
2773}
2774
2775void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2776 result.append("Buffering stats:\n");
2777 result.append(" [Layer name] <Active time> <Two buffer> "
2778 "<Double buffered> <Triple buffered>\n");
2779 Mutex::Autolock lock(mBufferingStatsMutex);
2780 typedef std::tuple<std::string, float, float, float> BufferTuple;
2781 std::map<float, BufferTuple, std::greater<float>> sorted;
2782 for (const auto& statsPair : mBufferingStats) {
2783 const char* name = statsPair.first.c_str();
2784 const BufferingStats& stats = statsPair.second;
2785 if (stats.numSegments == 0) {
2786 continue;
2787 }
2788 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2789 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2790 stats.totalTime;
2791 float doubleBufferRatio = static_cast<float>(
2792 stats.doubleBufferedTime) / stats.totalTime;
2793 float tripleBufferRatio = static_cast<float>(
2794 stats.tripleBufferedTime) / stats.totalTime;
2795 sorted.insert({activeTime, {name, twoBufferRatio,
2796 doubleBufferRatio, tripleBufferRatio}});
2797 }
2798 for (const auto& sortedPair : sorted) {
2799 float activeTime = sortedPair.first;
2800 const BufferTuple& values = sortedPair.second;
2801 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2802 std::get<0>(values).c_str(), activeTime,
2803 std::get<1>(values), std::get<2>(values),
2804 std::get<3>(values));
2805 }
2806 result.append("\n");
2807}
2808
2809
Mathias Agopian74d211a2013-04-22 16:55:35 +02002810void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2811 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002812{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002813 bool colorize = false;
2814 if (index < args.size()
2815 && (args[index] == String16("--color"))) {
2816 colorize = true;
2817 index++;
2818 }
2819
2820 Colorizer colorizer(colorize);
2821
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002822 // figure out if we're stuck somewhere
2823 const nsecs_t now = systemTime();
2824 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2825 const nsecs_t inTransaction(mDebugInTransaction);
2826 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2827 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2828
2829 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002830 * Dump library configuration.
2831 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002832
2833 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002834 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002835 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002836 appendSfConfigString(result);
2837 appendUiConfigString(result);
2838 appendGuiConfigString(result);
2839 result.append("\n");
2840
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002841 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002842 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002843 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002844 result.append(SyncFeatures::getInstance().toString());
2845 result.append("\n");
2846
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2848
Andy McFadden41d67d72014-04-25 16:58:34 -07002849 colorizer.bold(result);
2850 result.append("DispSync configuration: ");
2851 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002852 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2853 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2855 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002856 result.append("\n");
2857
Dan Stozab90cf072015-03-05 11:05:59 -08002858 // Dump static screen stats
2859 result.append("\n");
2860 dumpStaticScreenStats(result);
2861 result.append("\n");
2862
Dan Stozae77c7662016-05-13 11:37:28 -07002863 dumpBufferingStats(result);
2864
Andy McFadden4803b742012-09-24 19:07:20 -07002865 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002866 * Dump the visible layer list
2867 */
2868 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2869 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002870 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002871 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002872 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002873 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002874 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002875 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002876 }
2877
2878 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002879 * Dump Display state
2880 */
2881
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002882 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002883 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002884 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002885 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2886 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002887 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002888 }
2889
2890 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002891 * Dump SurfaceFlinger global state
2892 */
2893
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002894 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002895 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002896 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002897
Mathias Agopian888c8222012-08-04 21:10:38 -07002898 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002899 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002900
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002901 colorizer.bold(result);
2902 result.appendFormat("EGL implementation : %s\n",
2903 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2904 colorizer.reset(result);
2905 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002906 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002907
Mathias Agopian875d8e12013-06-07 15:35:48 -07002908 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002909
Mathias Agopian42977342012-08-05 00:40:46 -07002910 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002911 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2912 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002913 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002914 " last eglSwapBuffers() time: %f us\n"
2915 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002916 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002917 " refresh-rate : %f fps\n"
2918 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002919 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002920 " gpu_to_cpu_unsupported : %d\n"
2921 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002922 mLastSwapBufferTime/1000.0,
2923 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002924 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002925 1e9 / activeConfig->getVsyncPeriod(),
2926 activeConfig->getDpiX(),
2927 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002928 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002929
Mathias Agopian74d211a2013-04-22 16:55:35 +02002930 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002931 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002932
Mathias Agopian74d211a2013-04-22 16:55:35 +02002933 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002934 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002935
2936 /*
2937 * VSYNC state
2938 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002939 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002940
2941 /*
2942 * Dump HWComposer state
2943 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002944 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002945 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002946 colorizer.reset(result);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2948 mHasColorMatrix;
2949 result.appendFormat(" h/w composer %s\n",
2950 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002951 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002952
2953 /*
2954 * Dump gralloc state
2955 */
2956 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2957 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002958}
2959
Mathias Agopian13127d82013-03-05 17:47:11 -08002960const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002961SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002962 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002963 wp<IBinder> dpy;
2964 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2965 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2966 dpy = mDisplays.keyAt(i);
2967 break;
2968 }
2969 }
2970 if (dpy == NULL) {
2971 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2972 // Just use the primary display so we have something to return
2973 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2974 }
2975 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002976}
2977
Keun young Park63f165f2012-08-31 10:53:36 -07002978bool SurfaceFlinger::startDdmConnection()
2979{
2980 void* libddmconnection_dso =
2981 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2982 if (!libddmconnection_dso) {
2983 return false;
2984 }
2985 void (*DdmConnection_start)(const char* name);
2986 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002987 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002988 if (!DdmConnection_start) {
2989 dlclose(libddmconnection_dso);
2990 return false;
2991 }
2992 (*DdmConnection_start)(getServiceName());
2993 return true;
2994}
2995
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996status_t SurfaceFlinger::onTransact(
2997 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2998{
2999 switch (code) {
3000 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003001 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003002 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003004 case CLEAR_ANIMATION_FRAME_STATS:
3005 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003007 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 {
3009 // codes that require permission check
3010 IPCThreadState* ipc = IPCThreadState::self();
3011 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003012 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003013 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003014 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003015 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003016 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3017 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003019 break;
3020 }
3021 case CAPTURE_SCREEN:
3022 {
3023 // codes that require permission check
3024 IPCThreadState* ipc = IPCThreadState::self();
3025 const int pid = ipc->getCallingPid();
3026 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003027 if ((uid != AID_GRAPHICS) &&
3028 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003029 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003030 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3031 return PERMISSION_DENIED;
3032 }
3033 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034 }
3035 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3038 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003039 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003040 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003041 IPCThreadState* ipc = IPCThreadState::self();
3042 const int pid = ipc->getCallingPid();
3043 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003044 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003045 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 return PERMISSION_DENIED;
3047 }
3048 int n;
3049 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003050 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003051 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 return NO_ERROR;
3053 case 1002: // SHOW_UPDATES
3054 n = data.readInt32();
3055 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003056 invalidateHwcGeometry();
3057 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003060 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003061 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003063 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 setTransactionFlags(
3065 eTransactionNeeded|
3066 eDisplayTransactionNeeded|
3067 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003068 return NO_ERROR;
3069 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003070 case 1006:{ // send empty update
3071 signalRefresh();
3072 return NO_ERROR;
3073 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003074 case 1008: // toggle use of hw composer
3075 n = data.readInt32();
3076 mDebugDisableHWC = n ? 1 : 0;
3077 invalidateHwcGeometry();
3078 repaintEverything();
3079 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003080 case 1009: // toggle use of transform hint
3081 n = data.readInt32();
3082 mDebugDisableTransformHint = n ? 1 : 0;
3083 invalidateHwcGeometry();
3084 repaintEverything();
3085 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003087 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 reply->writeInt32(0);
3089 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003090 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003091 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 return NO_ERROR;
3093 case 1013: {
3094 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003095 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3096 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003097 return NO_ERROR;
3098 }
3099 case 1014: {
3100 // daltonize
3101 n = data.readInt32();
3102 switch (n % 10) {
3103 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3104 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3105 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3106 }
3107 if (n >= 10) {
3108 mDaltonizer.setMode(Daltonizer::correction);
3109 } else {
3110 mDaltonizer.setMode(Daltonizer::simulation);
3111 }
3112 mDaltonize = n > 0;
3113 invalidateHwcGeometry();
3114 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003115 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003117 case 1015: {
3118 // apply a color matrix
3119 n = data.readInt32();
3120 mHasColorMatrix = n ? 1 : 0;
3121 if (n) {
3122 // color matrix is sent as mat3 matrix followed by vec3
3123 // offset, then packed into a mat4 where the last row is
3124 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003125 for (size_t i = 0 ; i < 4; i++) {
3126 for (size_t j = 0; j < 4; j++) {
3127 mColorMatrix[i][j] = data.readFloat();
3128 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003129 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003130 } else {
3131 mColorMatrix = mat4();
3132 }
3133 invalidateHwcGeometry();
3134 repaintEverything();
3135 return NO_ERROR;
3136 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003137 // This is an experimental interface
3138 // Needs to be shifted to proper binder interface when we productize
3139 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003140 n = data.readInt32();
3141 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003142 return NO_ERROR;
3143 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003144 case 1017: {
3145 n = data.readInt32();
3146 mForceFullDamage = static_cast<bool>(n);
3147 return NO_ERROR;
3148 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003149 case 1018: { // Modify Choreographer's phase offset
3150 n = data.readInt32();
3151 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3152 return NO_ERROR;
3153 }
3154 case 1019: { // Modify SurfaceFlinger's phase offset
3155 n = data.readInt32();
3156 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3157 return NO_ERROR;
3158 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 }
3160 }
3161 return err;
3162}
3163
Mathias Agopian53331da2011-08-22 21:44:41 -07003164void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003165 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003166 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003167}
3168
Mathias Agopian59119e62010-10-11 12:37:43 -07003169// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003170// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003171// ---------------------------------------------------------------------------
3172
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003173/* The code below is here to handle b/8734824
3174 *
3175 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003176 * from the surfaceflinger thread to the calling binder thread, where they
3177 * are executed. This allows the calling thread in the calling process to be
3178 * reused and not depend on having "enough" binder threads to handle the
3179 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003180 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003181class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003182 /* Parts of GraphicProducerWrapper are run on two different threads,
3183 * communicating by sending messages via Looper but also by shared member
3184 * data. Coherence maintenance is subtle and in places implicit (ugh).
3185 *
3186 * Don't rely on Looper's sendMessage/handleMessage providing
3187 * release/acquire semantics for any data not actually in the Message.
3188 * Data going from surfaceflinger to binder threads needs to be
3189 * synchronized explicitly.
3190 *
3191 * Barrier open/wait do provide release/acquire semantics. This provides
3192 * implicit synchronization for data coming back from binder to
3193 * surfaceflinger threads.
3194 */
3195
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003196 sp<IGraphicBufferProducer> impl;
3197 sp<Looper> looper;
3198 status_t result;
3199 bool exitPending;
3200 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003201 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003202 uint32_t code;
3203 Parcel const* data;
3204 Parcel* reply;
3205
3206 enum {
3207 MSG_API_CALL,
3208 MSG_EXIT
3209 };
3210
3211 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003212 * Called on surfaceflinger thread. This is called by our "fake"
3213 * BpGraphicBufferProducer. We package the data and reply Parcel and
3214 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003215 */
3216 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003217 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003218 this->code = code;
3219 this->data = &data;
3220 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003221 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003222 // if we've exited, we run the message synchronously right here.
3223 // note (JH): as far as I can tell from looking at the code, this
3224 // never actually happens. if it does, i'm not sure if it happens
3225 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003226 handleMessage(Message(MSG_API_CALL));
3227 } else {
3228 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003229 // Prevent stores to this->{code, data, reply} from being
3230 // reordered later than the construction of Message.
3231 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003232 looper->sendMessage(this, Message(MSG_API_CALL));
3233 barrier.wait();
3234 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003235 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003236 }
3237
3238 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003239 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003240 * call the real BpGraphicBufferProducer.
3241 */
3242 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003243 int what = message.what;
3244 // Prevent reads below from happening before the read from Message
3245 atomic_thread_fence(memory_order_acquire);
3246 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003247 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003248 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003249 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003250 exitRequested = true;
3251 }
3252 }
3253
3254public:
Jesse Hallb154c422014-07-13 12:47:02 -07003255 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3256 : impl(impl),
3257 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003258 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003259 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003260 exitRequested(false),
3261 code(0),
3262 data(NULL),
3263 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003264 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003265
Jesse Hallb154c422014-07-13 12:47:02 -07003266 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003267 status_t waitForResponse() {
3268 do {
3269 looper->pollOnce(-1);
3270 } while (!exitRequested);
3271 return result;
3272 }
3273
Jesse Hallb154c422014-07-13 12:47:02 -07003274 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003275 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003276 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003277 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003278 // Ensure this->result is visible to the binder thread before it
3279 // handles the message.
3280 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003281 looper->sendMessage(this, Message(MSG_EXIT));
3282 }
3283};
3284
3285
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003286status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3287 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003288 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003289 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003290 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003291
3292 if (CC_UNLIKELY(display == 0))
3293 return BAD_VALUE;
3294
3295 if (CC_UNLIKELY(producer == 0))
3296 return BAD_VALUE;
3297
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003298 // if we have secure windows on this display, never allow the screen capture
3299 // unless the producer interface is local (i.e.: we can take a screenshot for
3300 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003301 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003302
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003303 // Convert to surfaceflinger's internal rotation type.
3304 Transform::orientation_flags rotationFlags;
3305 switch (rotation) {
3306 case ISurfaceComposer::eRotateNone:
3307 rotationFlags = Transform::ROT_0;
3308 break;
3309 case ISurfaceComposer::eRotate90:
3310 rotationFlags = Transform::ROT_90;
3311 break;
3312 case ISurfaceComposer::eRotate180:
3313 rotationFlags = Transform::ROT_180;
3314 break;
3315 case ISurfaceComposer::eRotate270:
3316 rotationFlags = Transform::ROT_270;
3317 break;
3318 default:
3319 rotationFlags = Transform::ROT_0;
3320 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3321 break;
3322 }
3323
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003324 class MessageCaptureScreen : public MessageBase {
3325 SurfaceFlinger* flinger;
3326 sp<IBinder> display;
3327 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003328 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003329 uint32_t reqWidth, reqHeight;
3330 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003331 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003332 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003333 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003334 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003335 public:
3336 MessageCaptureScreen(SurfaceFlinger* flinger,
3337 const sp<IBinder>& display,
3338 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003339 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003340 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003341 bool useIdentityTransform,
3342 Transform::orientation_flags rotation,
3343 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003344 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003345 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003346 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003347 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003348 rotation(rotation), result(PERMISSION_DENIED),
3349 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003350 {
3351 }
3352 status_t getResult() const {
3353 return result;
3354 }
3355 virtual bool handler() {
3356 Mutex::Autolock _l(flinger->mStateLock);
3357 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003358 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003359 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003360 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003361 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003362 return true;
3363 }
3364 };
3365
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003366 // this creates a "fake" BBinder which will serve as a "fake" remote
3367 // binder to receive the marshaled calls and forward them to the
3368 // real remote (a BpGraphicBufferProducer)
3369 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3370
3371 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3372 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003373 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003374 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003375 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003376 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003377
3378 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003379 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003380 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003381 }
3382 return res;
3383}
3384
Mathias Agopian180f10d2013-04-10 22:55:41 -07003385
3386void SurfaceFlinger::renderScreenImplLocked(
3387 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003388 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003389 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003390 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003391{
3392 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003393 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003394
3395 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003396 const int32_t hw_w = hw->getWidth();
3397 const int32_t hw_h = hw->getHeight();
3398 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003399 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003400
Dan Stozac1879002014-05-22 15:59:05 -07003401 // if a default or invalid sourceCrop is passed in, set reasonable values
3402 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3403 !sourceCrop.isValid()) {
3404 sourceCrop.setLeftTop(Point(0, 0));
3405 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3406 }
3407
3408 // ensure that sourceCrop is inside screen
3409 if (sourceCrop.left < 0) {
3410 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3411 }
Dan Stozabe31f442014-06-11 11:20:54 -07003412 if (sourceCrop.right > hw_w) {
3413 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003414 }
3415 if (sourceCrop.top < 0) {
3416 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3417 }
Dan Stozabe31f442014-06-11 11:20:54 -07003418 if (sourceCrop.bottom > hw_h) {
3419 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003420 }
3421
Mathias Agopian180f10d2013-04-10 22:55:41 -07003422 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003423 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003424
3425 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003426 engine.setViewportAndProjection(
3427 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003428 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003429
3430 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003431 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003432
3433 const LayerVector& layers( mDrawingState.layersSortedByZ );
3434 const size_t count = layers.size();
3435 for (size_t i=0 ; i<count ; ++i) {
3436 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003437 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003438 if (state.layerStack == hw->getLayerStack()) {
3439 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3440 if (layer->isVisible()) {
3441 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003442 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003443 if (filtering) layer->setFiltering(false);
3444 }
3445 }
3446 }
3447 }
3448
Mathias Agopian931bda12013-08-28 18:11:46 -07003449 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003450}
3451
3452
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003453status_t SurfaceFlinger::captureScreenImplLocked(
3454 const sp<const DisplayDevice>& hw,
3455 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003456 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003457 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003458 bool useIdentityTransform, Transform::orientation_flags rotation,
3459 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003460{
3461 ATRACE_CALL();
3462
Mathias Agopian180f10d2013-04-10 22:55:41 -07003463 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003464 uint32_t hw_w = hw->getWidth();
3465 uint32_t hw_h = hw->getHeight();
3466
3467 if (rotation & Transform::ROT_90) {
3468 std::swap(hw_w, hw_h);
3469 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003470
Mathias Agopian180f10d2013-04-10 22:55:41 -07003471 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3472 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3473 reqWidth, reqHeight, hw_w, hw_h);
3474 return BAD_VALUE;
3475 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003476
Mathias Agopian180f10d2013-04-10 22:55:41 -07003477 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3478 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3479
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003480 bool secureLayerIsVisible = false;
3481 const LayerVector& layers(mDrawingState.layersSortedByZ);
3482 const size_t count = layers.size();
3483 for (size_t i = 0 ; i < count ; ++i) {
3484 const sp<Layer>& layer(layers[i]);
3485 const Layer::State& state(layer->getDrawingState());
3486 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3487 state.z <= maxLayerZ && layer->isVisible() &&
3488 layer->isSecure()) {
3489 secureLayerIsVisible = true;
3490 }
3491 }
3492
3493 if (!isLocalScreenshot && secureLayerIsVisible) {
3494 ALOGW("FB is protected: PERMISSION_DENIED");
3495 return PERMISSION_DENIED;
3496 }
3497
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003498 // create a surface (because we're a producer, and we need to
3499 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003500 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003501 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003502
Michael Lentine5a16a622015-05-21 13:48:24 -07003503 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3504 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003505 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3506 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003507
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003508 int err = 0;
3509 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003510 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003511 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3512 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003513
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003514 if (err == NO_ERROR) {
3515 ANativeWindowBuffer* buffer;
3516 /* TODO: Once we have the sync framework everywhere this can use
3517 * server-side waits on the fence that dequeueBuffer returns.
3518 */
3519 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3520 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003521 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003522 // create an EGLImage from the buffer so we can later
3523 // turn it into a texture
3524 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3525 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3526 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003527 // this binds the given EGLImage as a framebuffer for the
3528 // duration of this scope.
3529 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3530 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003531 // this will in fact render into our dequeued buffer
3532 // via an FBO, which means we didn't have to create
3533 // an EGLSurface and therefore we're not
3534 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003535 renderScreenImplLocked(
3536 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3537 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003538
Riley Andrews86639902014-08-15 12:27:24 -07003539 // Attempt to create a sync khr object that can produce a sync point. If that
3540 // isn't available, create a non-dupable sync object in the fallback path and
3541 // wait on it directly.
3542 EGLSyncKHR sync;
3543 if (!DEBUG_SCREENSHOTS) {
3544 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003545 // native fence fd will not be populated until flush() is done.
3546 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003547 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003548 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003549 }
Riley Andrews86639902014-08-15 12:27:24 -07003550 if (sync != EGL_NO_SYNC_KHR) {
3551 // get the sync fd
3552 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3553 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3554 ALOGW("captureScreen: failed to dup sync khr object");
3555 syncFd = -1;
3556 }
3557 eglDestroySyncKHR(mEGLDisplay, sync);
3558 } else {
3559 // fallback path
3560 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3561 if (sync != EGL_NO_SYNC_KHR) {
3562 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3563 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3564 EGLint eglErr = eglGetError();
3565 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3566 ALOGW("captureScreen: fence wait timed out");
3567 } else {
3568 ALOGW_IF(eglErr != EGL_SUCCESS,
3569 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3570 }
3571 eglDestroySyncKHR(mEGLDisplay, sync);
3572 } else {
3573 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3574 }
3575 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003576 if (DEBUG_SCREENSHOTS) {
3577 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3578 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3579 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3580 hw, minLayerZ, maxLayerZ);
3581 delete [] pixels;
3582 }
3583
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003584 } else {
3585 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3586 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003587 window->cancelBuffer(window, buffer, syncFd);
3588 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003589 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003590 // destroy our image
3591 eglDestroyImageKHR(mEGLDisplay, image);
3592 } else {
3593 result = BAD_VALUE;
3594 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003595 if (buffer) {
3596 // queueBuffer takes ownership of syncFd
3597 result = window->queueBuffer(window, buffer, syncFd);
3598 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003599 }
3600 } else {
3601 result = BAD_VALUE;
3602 }
3603 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3604 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003605
Mathias Agopian74c40c02010-09-29 13:02:36 -07003606 return result;
3607}
3608
Mathias Agopiand5556842013-09-19 17:08:37 -07003609void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3610 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003611 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003612 for (size_t y=0 ; y<h ; y++) {
3613 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3614 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003615 if (p[x] != 0xFF000000) return;
3616 }
3617 }
3618 ALOGE("*** we just took a black screenshot ***\n"
3619 "requested minz=%d, maxz=%d, layerStack=%d",
3620 minLayerZ, maxLayerZ, hw->getLayerStack());
3621 const LayerVector& layers( mDrawingState.layersSortedByZ );
3622 const size_t count = layers.size();
3623 for (size_t i=0 ; i<count ; ++i) {
3624 const sp<Layer>& layer(layers[i]);
3625 const Layer::State& state(layer->getDrawingState());
3626 const bool visible = (state.layerStack == hw->getLayerStack())
3627 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3628 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003629 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003630 visible ? '+' : '-',
3631 i, layer->getName().string(), state.layerStack, state.z,
3632 layer->isVisible(), state.flags, state.alpha);
3633 }
3634 }
3635}
3636
Pablo Ceballosce796e72016-02-04 19:10:51 -08003637bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3638 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3639 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3640}
3641
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003642// ---------------------------------------------------------------------------
3643
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003644SurfaceFlinger::LayerVector::LayerVector() {
3645}
3646
3647SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003648 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003649}
3650
3651int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3652 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003653{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003654 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003655 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3656 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003657
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003658 uint32_t ls = l->getCurrentState().layerStack;
3659 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003660 if (ls != rs)
3661 return ls - rs;
3662
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003663 uint32_t lz = l->getCurrentState().z;
3664 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003665 if (lz != rz)
3666 return lz - rz;
3667
3668 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003669}
3670
3671// ---------------------------------------------------------------------------
3672
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003673SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003674 : type(DisplayDevice::DISPLAY_ID_INVALID),
3675 layerStack(DisplayDevice::NO_LAYER_STACK),
3676 orientation(0),
3677 width(0),
3678 height(0),
3679 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003680}
3681
Pablo Ceballos53390e12015-08-04 11:25:59 -07003682SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3683 DisplayDevice::DisplayType type, bool isSecure)
3684 : type(type),
3685 layerStack(DisplayDevice::NO_LAYER_STACK),
3686 orientation(0),
3687 width(0),
3688 height(0),
3689 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003690 viewport.makeInvalid();
3691 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003692}
3693
3694// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003697
3698
3699#if defined(__gl_h_)
3700#error "don't include gl/gl.h in this file"
3701#endif
3702
3703#if defined(__gl2_h_)
3704#error "don't include gl2/gl2.h in this file"
3705#endif