blob: 66c2251c800a16fca9625049c3a02b5c250fc948 [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
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080019#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
22#include <math.h>
Keun young Park63f165f2012-08-31 10:53:36 -070023#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080024#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070025#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070026
27#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070034#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036
Mathias Agopianc666cae2012-07-25 18:56:13 -070037#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070038#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070039
Mathias Agopian921e6ac2012-07-23 23:11:29 -070040#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070041#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070042#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080044#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080045#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070046
47#include <ui/GraphicBufferAllocator.h>
48#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080050
Mathias Agopiancde87a32012-09-13 14:09:01 -070051#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052#include <utils/String8.h>
53#include <utils/String16.h>
54#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070055#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080056#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070059#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian3e25fd82013-04-22 17:52:16 +020061#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080064#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070065#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070066#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070067#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080068#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopiana4912602012-07-12 14:25:33 -070073#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070074#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070075#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopianff2ed702013-09-01 21:36:12 -070077#include "Effects/Daltonizer.h"
78
Mathias Agopian875d8e12013-06-07 15:35:48 -070079#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070080#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#define DISPLAY_COUNT 1
83
Mathias Agopianfee2b462013-07-03 12:34:01 -070084/*
85 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
86 * black pixels.
87 */
88#define DEBUG_SCREENSHOTS false
89
Mathias Agopianca088332013-03-28 17:44:13 -070090EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
91
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070093
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094// This is the phase offset in nanoseconds of the software vsync event
95// relative to the vsync event reported by HWComposer. The software vsync
96// event is when SurfaceFlinger and Choreographer-based applications run each
97// frame.
98//
99// This phase offset allows adjustment of the minimum latency from application
100// wake-up (by Choregographer) time to the time at which the resulting window
101// image is displayed. This value may be either positive (after the HW vsync)
102// or negative (before the HW vsync). Setting it to 0 will result in a
103// minimum latency of two vsync periods because the app and SurfaceFlinger
104// will run just after the HW vsync. Setting it to a positive number will
105// result in the minimum latency being:
106//
107// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
108//
109// Note that reducing this latency makes it more likely for the applications
110// to not have their window content image ready in time. When this happens
111// the latency will end up being an additional vsync period, and animations
112// will hiccup. Therefore, this latency should be tuned somewhat
113// conservatively (or at least with awareness of the trade-off being made).
114static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
115
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700116// This is the phase offset at which SurfaceFlinger's composition runs.
117static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119// ---------------------------------------------------------------------------
120
Mathias Agopian99b49842011-06-27 16:05:52 -0700121const String16 sHardwareTest("android.permission.HARDWARE_TEST");
122const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
123const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
124const String16 sDump("android.permission.DUMP");
125
126// ---------------------------------------------------------------------------
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700129 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700131 mTransactionPending(false),
132 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700133 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700134 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700135 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mVisibleRegionsDirty(false),
Mathias Agopiana350ff92010-08-10 17:14:02 -0700138 mHwWorkListDirty(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800139 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700141 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700142 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700143 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700144 mDebugInSwapBuffers(0),
145 mLastSwapBufferTime(0),
146 mDebugInTransaction(0),
147 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700148 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700149 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700150 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700151 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700152 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800153 mHasColorMatrix(false),
154 mHasPoweredOff(false),
155 mFrameBuckets(),
156 mTotalTime(0),
157 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158{
Steve Blocka19954a2012-01-04 20:05:49 +0000159 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160
161 // debugging stuff...
162 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700163
Mathias Agopianb4b17302013-03-20 18:36:41 -0700164 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700165 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700166
Dan Stoza14cd37c2015-07-09 12:43:33 -0700167 property_get("debug.sf.drop_missed_frames", value, "0");
168 mDropMissedFrames = atoi(value);
169
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) {
266 ALOGW_IF(mBuiltinDisplays[type],
267 "Overwriting display token for display type %d", type);
268 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800269 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700270 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800271 mCurrentState.displays.add(mBuiltinDisplays[type], info);
272}
273
Mathias Agopiane57f2922012-08-09 16:29:12 -0700274sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700275 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700276 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
277 return NULL;
278 }
Jesse Hall692c7232012-11-08 15:41:56 -0800279 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280}
281
Jamie Gennis9a78c902011-01-12 18:30:40 -0800282sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
283{
284 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
285 return gba;
286}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288void SurfaceFlinger::bootFinished()
289{
290 const nsecs_t now = systemTime();
291 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000292 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700293 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700294
295 // wait patiently for the window manager death
296 const String16 name("window");
297 sp<IBinder> window(defaultServiceManager()->getService(name));
298 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700299 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700300 }
301
302 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700303 // formerly we would just kill the process, but we now ask it to exit so it
304 // can choose where to stop the animation.
305 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700306
307 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
308 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
309 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Mathias Agopian3f844832013-08-07 21:24:32 -0700312void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700313 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700314 RenderEngine& engine;
315 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700316 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700317 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
318 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700319 }
320 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700321 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700322 return true;
323 }
324 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700326}
327
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700328class DispSyncSource : public VSyncSource, private DispSync::Callback {
329public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700330 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
331 const char* label) :
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700332 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700333 mTraceVsync(traceVsync),
Andy McFadden5167ec62014-05-22 13:08:43 -0700334 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
335 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700336 mDispSync(dispSync),
337 mCallbackMutex(),
338 mCallback(),
339 mVsyncMutex(),
340 mPhaseOffset(phaseOffset),
341 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700342
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700343 virtual ~DispSyncSource() {}
344
345 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700346 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700347 if (enable) {
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700348 status_t err = mDispSync->addEventListener(mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700349 static_cast<DispSync::Callback*>(this));
350 if (err != NO_ERROR) {
351 ALOGE("error registering vsync callback: %s (%d)",
352 strerror(-err), err);
353 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700354 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700355 } else {
356 status_t err = mDispSync->removeEventListener(
357 static_cast<DispSync::Callback*>(this));
358 if (err != NO_ERROR) {
359 ALOGE("error unregistering vsync callback: %s (%d)",
360 strerror(-err), err);
361 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700362 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700364 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 }
366
367 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700368 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 mCallback = callback;
370 }
371
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700372 virtual void setPhaseOffset(nsecs_t phaseOffset) {
373 Mutex::Autolock lock(mVsyncMutex);
374
375 // Normalize phaseOffset to [0, period)
376 auto period = mDispSync->getPeriod();
377 phaseOffset %= period;
378 if (phaseOffset < 0) {
379 // If we're here, then phaseOffset is in (-period, 0). After this
380 // operation, it will be in (0, period)
381 phaseOffset += period;
382 }
383 mPhaseOffset = phaseOffset;
384
385 // If we're not enabled, we don't need to mess with the listeners
386 if (!mEnabled) {
387 return;
388 }
389
390 // Remove the listener with the old offset
391 status_t err = mDispSync->removeEventListener(
392 static_cast<DispSync::Callback*>(this));
393 if (err != NO_ERROR) {
394 ALOGE("error unregistering vsync callback: %s (%d)",
395 strerror(-err), err);
396 }
397
398 // Add a listener with the new offset
399 err = mDispSync->addEventListener(mPhaseOffset,
400 static_cast<DispSync::Callback*>(this));
401 if (err != NO_ERROR) {
402 ALOGE("error registering vsync callback: %s (%d)",
403 strerror(-err), err);
404 }
405 }
406
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700407private:
408 virtual void onDispSyncEvent(nsecs_t when) {
409 sp<VSyncSource::Callback> callback;
410 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700411 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 callback = mCallback;
413
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700414 if (mTraceVsync) {
415 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700416 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700417 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 }
419
420 if (callback != NULL) {
421 callback->onVSyncEvent(when);
422 }
423 }
424
425 int mValue;
426
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700427 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 const String8 mVsyncOnLabel;
429 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700430
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700432
433 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435
436 Mutex mVsyncMutex; // Protects the following
437 nsecs_t mPhaseOffset;
438 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439};
440
441void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700442 ALOGI( "SurfaceFlinger's main thread ready to run. "
443 "Initializing graphics H/W...");
444
Jesse Hall692c7232012-11-08 15:41:56 -0800445 Mutex::Autolock _l(mStateLock);
446
Andy McFaddenb0d1dd32012-09-10 14:08:09 -0700447 // initialize EGL for the default display
Jesse Hall34a09ba2012-07-29 22:35:34 -0700448 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
449 eglInitialize(mEGLDisplay, NULL, NULL);
Mathias Agopiana4912602012-07-12 14:25:33 -0700450
Saurabh Shahf9481052015-06-15 17:55:51 -0700451 // start the EventThread
452 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
453 vsyncPhaseOffsetNs, true, "app");
454 mEventThread = new EventThread(vsyncSrc);
455 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
456 sfVsyncPhaseOffsetNs, true, "sf");
457 mSFEventThread = new EventThread(sfVsyncSrc);
458 mEventQueue.setEventThread(mSFEventThread);
459
Andy McFaddenb0d1dd32012-09-10 14:08:09 -0700460 // Initialize the H/W composer object. There may or may not be an
461 // actual hardware composer underneath.
462 mHwc = new HWComposer(this,
463 *static_cast<HWComposer::EventHandler *>(this));
464
Mathias Agopian875d8e12013-06-07 15:35:48 -0700465 // get a RenderEngine for the given display / config (can't fail)
Jesse Hall05f8c702013-12-23 20:44:38 -0800466 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
Mathias Agopian875d8e12013-06-07 15:35:48 -0700467
468 // retrieve the EGL context that was selected/created
469 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700470
Mathias Agopianda27af92012-09-13 18:17:13 -0700471 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
472 "couldn't create EGLContext");
473
Mathias Agopiancde87a32012-09-13 14:09:01 -0700474 // initialize our non-virtual displays
Jesse Hall9e663de2013-08-16 14:28:37 -0700475 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Mathias Agopianf5a33922012-09-19 18:16:22 -0700476 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700477 // set-up the displays that are already connected
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700478 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700479 // All non-virtual displays are currently considered secure.
480 bool isSecure = true;
Jesse Hall692c7232012-11-08 15:41:56 -0800481 createBuiltinDisplayLocked(type);
482 wp<IBinder> token = mBuiltinDisplays[i];
483
Dan Stozab9b08832014-03-13 11:55:57 -0700484 sp<IGraphicBufferProducer> producer;
485 sp<IGraphicBufferConsumer> consumer;
Dan Stozaacd56152016-01-08 09:36:21 -0800486 BufferQueue::createBufferQueue(&producer, &consumer);
Dan Stozab9b08832014-03-13 11:55:57 -0700487
488 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
489 consumer);
Jesse Hall19e87292013-12-23 21:02:15 -0800490 int32_t hwcId = allocateHwcDisplayId(type);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700491 sp<DisplayDevice> hw = new DisplayDevice(this,
Jesse Hall19e87292013-12-23 21:02:15 -0800492 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
Dan Stozab9b08832014-03-13 11:55:57 -0700493 fbs, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -0800494 mRenderEngine->getEGLConfig());
Mathias Agopianf5a33922012-09-19 18:16:22 -0700495 if (i > DisplayDevice::DISPLAY_PRIMARY) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -0700496 // FIXME: currently we don't get blank/unblank requests
Mathias Agopianf5a33922012-09-19 18:16:22 -0700497 // for displays other than the main display, so we always
498 // assume a connected display is unblanked.
Greg Hackmann86efcc02014-03-07 12:44:02 -0800499 ALOGD("marking display %zu as acquired/unblanked", i);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700500 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700501 }
502 mDisplays.add(token, hw);
503 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 }
Mathias Agopiancde87a32012-09-13 14:09:01 -0700505
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700506 // make the GLContext current so that we can create textures when creating Layers
507 // (which may happens before we render something)
508 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
509
Jamie Gennisd1700752013-10-14 12:22:52 -0700510 mEventControlThread = new EventControlThread(this);
511 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
512
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513 // set a fake vsync period if there is no HWComposer
514 if (mHwc->initCheck() != NO_ERROR) {
515 mPrimaryDispSync.setPeriod(16666667);
516 }
517
Mathias Agopian92a979a2012-08-02 18:32:23 -0700518 // initialize our drawing state
519 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700520
Andy McFadden13a082e2012-08-24 10:16:42 -0700521 // set initial conditions (e.g. unblank default device)
522 initializeDisplays();
523
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700524 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700525 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526}
527
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700528int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700529 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700530 type : mHwc->allocateDisplayId();
531}
532
Mathias Agopiana67e4182012-06-19 17:26:12 -0700533void SurfaceFlinger::startBootAnim() {
534 // start boot animation
535 property_set("service.bootanim.exit", "0");
536 property_set("ctl.start", "bootanim");
537}
538
Mathias Agopian875d8e12013-06-07 15:35:48 -0700539size_t SurfaceFlinger::getMaxTextureSize() const {
540 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700541}
542
Mathias Agopian875d8e12013-06-07 15:35:48 -0700543size_t SurfaceFlinger::getMaxViewportDims() const {
544 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800548
Jamie Gennis582270d2011-08-17 18:19:00 -0700549bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800550 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800551 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800552 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700553 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800554}
555
Dan Stoza7f7da322014-05-02 15:26:25 -0700556status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
557 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700558 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700559 return BAD_VALUE;
560 }
561
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500562 if (!display.get())
563 return NAME_NOT_FOUND;
564
Jesse Hall692c7232012-11-08 15:41:56 -0800565 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700566 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800567 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700568 type = i;
569 break;
570 }
571 }
572
573 if (type < 0) {
574 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700575 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700576
Mathias Agopian8b736f12012-08-13 17:54:26 -0700577 // TODO: Not sure if display density should handled by SF any longer
578 class Density {
579 static int getDensityFromProperty(char const* propName) {
580 char property[PROPERTY_VALUE_MAX];
581 int density = 0;
582 if (property_get(propName, property, NULL) > 0) {
583 density = atoi(property);
584 }
585 return density;
586 }
587 public:
588 static int getEmuDensity() {
589 return getDensityFromProperty("qemu.sf.lcd_density"); }
590 static int getBuildDensity() {
591 return getDensityFromProperty("ro.sf.lcd_density"); }
592 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700593
Dan Stoza7f7da322014-05-02 15:26:25 -0700594 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700595
Dan Stoza7f7da322014-05-02 15:26:25 -0700596 const Vector<HWComposer::DisplayConfig>& hwConfigs =
597 getHwComposer().getConfigs(type);
598 for (size_t c = 0; c < hwConfigs.size(); ++c) {
599 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
600 DisplayInfo info = DisplayInfo();
601
602 float xdpi = hwConfig.xdpi;
603 float ydpi = hwConfig.ydpi;
604
605 if (type == DisplayDevice::DISPLAY_PRIMARY) {
606 // The density of the device is provided by a build property
607 float density = Density::getBuildDensity() / 160.0f;
608 if (density == 0) {
609 // the build doesn't provide a density -- this is wrong!
610 // use xdpi instead
611 ALOGE("ro.sf.lcd_density must be defined as a build property");
612 density = xdpi / 160.0f;
613 }
614 if (Density::getEmuDensity()) {
615 // if "qemu.sf.lcd_density" is specified, it overrides everything
616 xdpi = ydpi = density = Density::getEmuDensity();
617 density /= 160.0f;
618 }
619 info.density = density;
620
621 // TODO: this needs to go away (currently needed only by webkit)
622 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
623 info.orientation = hw->getOrientation();
624 } else {
625 // TODO: where should this value come from?
626 static const int TV_DENSITY = 213;
627 info.density = TV_DENSITY / 160.0f;
628 info.orientation = 0;
629 }
630
631 info.w = hwConfig.width;
632 info.h = hwConfig.height;
633 info.xdpi = xdpi;
634 info.ydpi = ydpi;
635 info.fps = float(1e9 / hwConfig.refresh);
Andy McFadden91b2ca82014-06-13 14:04:23 -0700636 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stozaf2699fc2015-08-31 12:06:48 -0700637 info.colorTransform = hwConfig.colorTransform;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700638
639 // This is how far in advance a buffer must be queued for
640 // presentation at a given time. If you want a buffer to appear
641 // on the screen at time N, you must submit the buffer before
642 // (N - presentationDeadline).
643 //
644 // Normally it's one full refresh period (to give SF a chance to
645 // latch the buffer), but this can be reduced by configuring a
646 // DispSync offset. Any additional delays introduced by the hardware
647 // composer or panel must be accounted for here.
648 //
649 // We add an additional 1ms to allow for processing time and
650 // differences between the ideal and actual refresh rate.
651 info.presentationDeadline =
652 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700653
654 // All non-virtual displays are currently considered secure.
655 info.secure = true;
656
657 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700658 }
659
Dan Stoza7f7da322014-05-02 15:26:25 -0700660 return NO_ERROR;
661}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700662
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800663status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700664 DisplayStatInfo* stats) {
665 if (stats == NULL) {
666 return BAD_VALUE;
667 }
668
669 // FIXME for now we always return stats for the primary display
670 memset(stats, 0, sizeof(*stats));
671 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
672 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
673 return NO_ERROR;
674}
675
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700676int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700677 sp<DisplayDevice> device(getDisplayDevice(display));
678 if (device != NULL) {
679 return device->getActiveConfig();
680 }
681 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700682}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700683
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700684void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
685 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
686 this);
687 int32_t type = hw->getDisplayType();
688 int currentMode = hw->getActiveConfig();
689
690 if (mode == currentMode) {
691 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
692 return;
693 }
694
695 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
696 ALOGW("Trying to set config for virtual display");
697 return;
698 }
699
700 hw->setActiveConfig(mode);
701 getHwComposer().setActiveConfig(type, mode);
702}
703
704status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
705 class MessageSetActiveConfig: public MessageBase {
706 SurfaceFlinger& mFlinger;
707 sp<IBinder> mDisplay;
708 int mMode;
709 public:
710 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
711 int mode) :
712 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
713 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700714 Vector<DisplayInfo> configs;
715 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700716 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700717 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700718 mMode, configs.size());
719 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700720 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
721 if (hw == NULL) {
722 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700723 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700724 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
725 ALOGW("Attempt to set active config = %d for virtual display",
726 mMode);
727 } else {
728 mFlinger.setActiveConfigInternal(hw, mMode);
729 }
730 return true;
731 }
732 };
733 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
734 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700735 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700736}
737
Svetoslavd85084b2014-03-20 10:28:31 -0700738status_t SurfaceFlinger::clearAnimationFrameStats() {
739 Mutex::Autolock _l(mStateLock);
740 mAnimFrameTracker.clearStats();
741 return NO_ERROR;
742}
743
744status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
745 Mutex::Autolock _l(mStateLock);
746 mAnimFrameTracker.getStats(outStats);
747 return NO_ERROR;
748}
749
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800750// ----------------------------------------------------------------------------
751
752sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800753 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800757
758void SurfaceFlinger::waitForEvent() {
759 mEventQueue.waitMessage();
760}
761
762void SurfaceFlinger::signalTransaction() {
763 mEventQueue.invalidate();
764}
765
766void SurfaceFlinger::signalLayerUpdate() {
767 mEventQueue.invalidate();
768}
769
770void SurfaceFlinger::signalRefresh() {
771 mEventQueue.refresh();
772}
773
774status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800775 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800776 return mEventQueue.postMessage(msg, reltime);
777}
778
779status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800780 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800781 status_t res = mEventQueue.postMessage(msg, reltime);
782 if (res == NO_ERROR) {
783 msg->wait();
784 }
785 return res;
786}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800787
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700788void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700789 do {
790 waitForEvent();
791 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800792}
793
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700794void SurfaceFlinger::enableHardwareVsync() {
795 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700796 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700797 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700798 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
799 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700800 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700801 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700802}
803
Jesse Hall948fe0c2013-10-14 12:56:09 -0700804void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700805 Mutex::Autolock _l(mHWVsyncLock);
806
Jesse Hall948fe0c2013-10-14 12:56:09 -0700807 if (makeAvailable) {
808 mHWVsyncAvailable = true;
809 } else if (!mHWVsyncAvailable) {
810 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
811 return;
812 }
813
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700814 const nsecs_t period =
815 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
816
817 mPrimaryDispSync.reset();
818 mPrimaryDispSync.setPeriod(period);
819
820 if (!mPrimaryHWVsyncEnabled) {
821 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700822 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
823 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700824 mPrimaryHWVsyncEnabled = true;
825 }
826}
827
Jesse Hall948fe0c2013-10-14 12:56:09 -0700828void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700829 Mutex::Autolock _l(mHWVsyncLock);
830 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700831 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
832 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700833 mPrimaryDispSync.endResync();
834 mPrimaryHWVsyncEnabled = false;
835 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700836 if (makeUnavailable) {
837 mHWVsyncAvailable = false;
838 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700839}
840
841void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700842 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700843
Jamie Gennisd1700752013-10-14 12:22:52 -0700844 { // Scope for the lock
845 Mutex::Autolock _l(mHWVsyncLock);
846 if (type == 0 && mPrimaryHWVsyncEnabled) {
847 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700848 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700849 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700850
851 if (needsHwVsync) {
852 enableHardwareVsync();
853 } else {
854 disableHardwareVsync(false);
855 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700856}
857
858void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
859 if (mEventThread == NULL) {
860 // This is a temporary workaround for b/7145521. A non-null pointer
861 // does not mean EventThread has finished initializing, so this
862 // is not a correct fix.
863 ALOGW("WARNING: EventThread not started, ignoring hotplug");
864 return;
865 }
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700866
Jesse Hall9e663de2013-08-16 14:28:37 -0700867 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700868 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800869 if (connected) {
870 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700871 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800872 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
873 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700874 }
875 setTransactionFlags(eDisplayTransactionNeeded);
876
Andy McFadden9e9689c2012-10-10 18:17:51 -0700877 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700878 }
Mathias Agopian86303202012-07-24 22:46:10 -0700879}
880
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700881void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700882 ATRACE_CALL();
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700883 getHwComposer().eventControl(disp, event, enabled);
Mathias Agopian86303202012-07-24 22:46:10 -0700884}
885
Mathias Agopian4fec8732012-06-29 14:12:52 -0700886void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800887 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800888 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800889 case MessageQueue::TRANSACTION: {
890 handleMessageTransaction();
891 break;
892 }
893 case MessageQueue::INVALIDATE: {
894 bool refreshNeeded = handleMessageTransaction();
895 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800896 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800897 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800898 // Signal a refresh if a transaction modified the window state,
899 // a new buffer was latched, or if HWC has requested a full
900 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800901 signalRefresh();
902 }
903 break;
904 }
905 case MessageQueue::REFRESH: {
906 handleMessageRefresh();
907 break;
908 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800909 }
910}
911
Dan Stoza6b9454d2014-11-07 16:00:59 -0800912bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700913 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700914 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700915 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800916 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700917 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800918 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700919}
920
Dan Stoza6b9454d2014-11-07 16:00:59 -0800921bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700922 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800923 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700924}
925
926void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700927 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700928
929 static nsecs_t previousExpectedPresent = 0;
930 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
931 static bool previousFrameMissed = false;
932 bool frameMissed = (expectedPresent == previousExpectedPresent);
933 if (frameMissed != previousFrameMissed) {
934 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
935 }
936 previousFrameMissed = frameMissed;
937
938 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
939 // Latch buffers, but don't send anything to HWC, then signal another
940 // wakeup for the next vsync
941 preComposition();
942 repaintEverything();
943 } else {
944 preComposition();
945 rebuildLayerStacks();
946 setUpHWComposer();
947 doDebugFlashRegions();
948 doComposition();
949 postComposition();
950 }
951
952 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700953}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700954
Mathias Agopiancd60f992012-08-16 16:28:27 -0700955void SurfaceFlinger::doDebugFlashRegions()
956{
957 // is debugging enabled
958 if (CC_LIKELY(!mDebugRegion))
959 return;
960
961 const bool repaintEverything = mRepaintEverything;
962 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
963 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700964 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700965 // transform the dirty region into this screen's coordinate space
966 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
967 if (!dirtyRegion.isEmpty()) {
968 // redraw the whole screen
969 doComposeSurfaces(hw, Region(hw->bounds()));
970
971 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700972 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -0700973 RenderEngine& engine(getRenderEngine());
974 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
975
Mathias Agopiancd60f992012-08-16 16:28:27 -0700976 hw->compositionComplete();
Mathias Agopianda27af92012-09-13 18:17:13 -0700977 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -0700978 }
979 }
980 }
981
982 postFramebuffer();
983
984 if (mDebugRegion > 1) {
985 usleep(mDebugRegion * 1000);
986 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -0700987
988 HWComposer& hwc(getHwComposer());
989 if (hwc.initCheck() == NO_ERROR) {
990 status_t err = hwc.prepare();
991 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
992 }
Mathias Agopiancd60f992012-08-16 16:28:27 -0700993}
994
995void SurfaceFlinger::preComposition()
996{
997 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700998 const LayerVector& layers(mDrawingState.layersSortedByZ);
999 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001000 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001001 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001002 needExtraInvalidate = true;
1003 }
1004 }
1005 if (needExtraInvalidate) {
1006 signalLayerUpdate();
1007 }
1008}
1009
1010void SurfaceFlinger::postComposition()
1011{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001012 const LayerVector& layers(mDrawingState.layersSortedByZ);
1013 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001014 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001015 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001016 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001017
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001018 const HWComposer& hwc = getHwComposer();
1019 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1020
1021 if (presentFence->isValid()) {
1022 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1023 enableHardwareVsync();
1024 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001025 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001026 }
1027 }
1028
Dan Stozab90cf072015-03-05 11:05:59 -08001029 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001030 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001031 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001032 enableHardwareVsync();
1033 }
1034 }
1035
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001036 if (mAnimCompositionPending) {
1037 mAnimCompositionPending = false;
1038
Jesse Halla9a1b002013-02-27 16:39:25 -08001039 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001040 mAnimFrameTracker.setActualPresentFence(presentFence);
1041 } else {
1042 // The HWC doesn't support present fences, so use the refresh
1043 // timestamp instead.
1044 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1045 mAnimFrameTracker.setActualPresentTime(presentTime);
1046 }
1047 mAnimFrameTracker.advanceFrame();
1048 }
Dan Stozab90cf072015-03-05 11:05:59 -08001049
1050 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1051 return;
1052 }
1053
1054 nsecs_t currentTime = systemTime();
1055 if (mHasPoweredOff) {
1056 mHasPoweredOff = false;
1057 } else {
1058 nsecs_t period = mPrimaryDispSync.getPeriod();
1059 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1060 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1061 if (numPeriods < NUM_BUCKETS - 1) {
1062 mFrameBuckets[numPeriods] += elapsedTime;
1063 } else {
1064 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1065 }
1066 mTotalTime += elapsedTime;
1067 }
1068 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001069}
1070
1071void SurfaceFlinger::rebuildLayerStacks() {
1072 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001073 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001074 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001075 mVisibleRegionsDirty = false;
1076 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001077
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001078 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001079 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001080 Region opaqueRegion;
1081 Region dirtyRegion;
Mathias Agopian13127d82013-03-05 17:47:11 -08001082 Vector< sp<Layer> > layersSortedByZ;
Mathias Agopian42977342012-08-05 00:40:46 -07001083 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001084 const Transform& tr(hw->getTransform());
1085 const Rect bounds(hw->getBounds());
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001086 if (hw->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001087 SurfaceFlinger::computeVisibleRegions(layers,
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001088 hw->getLayerStack(), dirtyRegion, opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001089
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001090 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001091 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001092 const sp<Layer>& layer(layers[i]);
1093 const Layer::State& s(layer->getDrawingState());
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001094 if (s.layerStack == hw->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001095 Region drawRegion(tr.transform(
1096 layer->visibleNonTransparentRegion));
1097 drawRegion.andSelf(bounds);
1098 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001099 layersSortedByZ.add(layer);
1100 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001101 }
1102 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001103 }
Mathias Agopian42977342012-08-05 00:40:46 -07001104 hw->setVisibleLayersSortedByZ(layersSortedByZ);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001105 hw->undefinedRegion.set(bounds);
1106 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1107 hw->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001108 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001109 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001110}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001111
Mathias Agopiancd60f992012-08-16 16:28:27 -07001112void SurfaceFlinger::setUpHWComposer() {
Jesse Hall028dc8f2013-08-20 16:35:32 -07001113 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001114 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1115 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1116 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1117
1118 // If nothing has changed (!dirty), don't recompose.
1119 // If something changed, but we don't currently have any visible layers,
1120 // and didn't when we last did a composition, then skip it this time.
1121 // The second rule does two things:
1122 // - When all layers are removed from a display, we'll emit one black
1123 // frame, then nothing more until we get new layers.
1124 // - When a display is created with a private layer stack, we won't
1125 // emit any black frames until a layer is added to the layer stack.
1126 bool mustRecompose = dirty && !(empty && wasEmpty);
1127
1128 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1129 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1130 mustRecompose ? "doing" : "skipping",
1131 dirty ? "+" : "-",
1132 empty ? "+" : "-",
1133 wasEmpty ? "+" : "-");
1134
Dan Stoza71433162014-02-04 16:22:36 -08001135 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001136
1137 if (mustRecompose) {
1138 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1139 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001140 }
1141
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001142 HWComposer& hwc(getHwComposer());
1143 if (hwc.initCheck() == NO_ERROR) {
1144 // build the h/w work list
Jamie Gennisa4310c82012-09-25 20:26:00 -07001145 if (CC_UNLIKELY(mHwWorkListDirty)) {
1146 mHwWorkListDirty = false;
1147 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1148 sp<const DisplayDevice> hw(mDisplays[dpy]);
1149 const int32_t id = hw->getHwcDisplayId();
1150 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001151 const Vector< sp<Layer> >& currentLayers(
Jamie Gennisa4310c82012-09-25 20:26:00 -07001152 hw->getVisibleLayersSortedByZ());
1153 const size_t count = currentLayers.size();
1154 if (hwc.createWorkList(id, count) == NO_ERROR) {
1155 HWComposer::LayerListIterator cur = hwc.begin(id);
1156 const HWComposer::LayerListIterator end = hwc.end(id);
1157 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001158 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001159 layer->setGeometry(hw, *cur);
Alan Viverette9c5a3332013-09-12 20:04:35 -07001160 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
Jamie Gennisa4310c82012-09-25 20:26:00 -07001161 cur->setSkip(true);
1162 }
1163 }
1164 }
1165 }
1166 }
1167 }
1168
1169 // set the per-frame data
Mathias Agopian92a979a2012-08-02 18:32:23 -07001170 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001171 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001172 const int32_t id = hw->getHwcDisplayId();
1173 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001174 const Vector< sp<Layer> >& currentLayers(
Mathias Agopiancd60f992012-08-16 16:28:27 -07001175 hw->getVisibleLayersSortedByZ());
Mathias Agopiane60b0682012-08-21 23:34:09 -07001176 const size_t count = currentLayers.size();
Jamie Gennisa4310c82012-09-25 20:26:00 -07001177 HWComposer::LayerListIterator cur = hwc.begin(id);
1178 const HWComposer::LayerListIterator end = hwc.end(id);
1179 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1180 /*
1181 * update the per-frame h/w composer data for each layer
1182 * and build the transparent region of the FB
1183 */
Mathias Agopian13127d82013-03-05 17:47:11 -08001184 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001185 layer->setPerFrameData(hw, *cur);
Mathias Agopian1e260872012-08-08 18:35:12 -07001186 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001187 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001188 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001189
Riley Andrews03414a12014-07-01 14:22:59 -07001190 // If possible, attempt to use the cursor overlay on each display.
1191 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1192 sp<const DisplayDevice> hw(mDisplays[dpy]);
1193 const int32_t id = hw->getHwcDisplayId();
1194 if (id >= 0) {
1195 const Vector< sp<Layer> >& currentLayers(
1196 hw->getVisibleLayersSortedByZ());
1197 const size_t count = currentLayers.size();
1198 HWComposer::LayerListIterator cur = hwc.begin(id);
1199 const HWComposer::LayerListIterator end = hwc.end(id);
1200 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1201 const sp<Layer>& layer(currentLayers[i]);
1202 if (layer->isPotentialCursor()) {
1203 cur->setIsCursorLayerHint();
1204 break;
1205 }
1206 }
1207 }
1208 }
1209
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001210 status_t err = hwc.prepare();
1211 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
Jesse Hall38efe862013-04-06 23:12:29 -07001212
1213 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1214 sp<const DisplayDevice> hw(mDisplays[dpy]);
1215 hw->prepareFrame(hwc);
1216 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001217 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001218}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001219
Mathias Agopiancd60f992012-08-16 16:28:27 -07001220void SurfaceFlinger::doComposition() {
1221 ATRACE_CALL();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001222 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001223 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001224 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001225 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001226 // transform the dirty region into this screen's coordinate space
1227 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001228
1229 // repaint the framebuffer (if needed)
1230 doDisplayComposition(hw, dirtyRegion);
1231
Mathias Agopiancd60f992012-08-16 16:28:27 -07001232 hw->dirtyRegion.clear();
1233 hw->flip(hw->swapRegion);
1234 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001235 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001236 // inform the h/w that we're done compositing
Mathias Agopian42977342012-08-05 00:40:46 -07001237 hw->compositionComplete();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001238 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001239 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001240}
1241
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242void SurfaceFlinger::postFramebuffer()
1243{
Mathias Agopian841cde52012-03-01 15:44:37 -08001244 ATRACE_CALL();
Mathias Agopianb048cef2012-02-04 15:44:04 -08001245
Mathias Agopiana44b0412011-10-16 18:46:35 -07001246 const nsecs_t now = systemTime();
1247 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001248
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001249 HWComposer& hwc(getHwComposer());
Jesse Hallef194142012-06-14 14:45:17 -07001250 if (hwc.initCheck() == NO_ERROR) {
Mathias Agopian2a231842012-09-24 18:12:35 -07001251 if (!hwc.supportsFramebufferTarget()) {
1252 // EGL spec says:
1253 // "surface must be bound to the calling thread's current context,
1254 // for the current rendering API."
Mathias Agopian875d8e12013-06-07 15:35:48 -07001255 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopian2a231842012-09-24 18:12:35 -07001256 }
Mathias Agopiane60b0682012-08-21 23:34:09 -07001257 hwc.commit();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001258 }
1259
Mathias Agopian6da15f42013-09-25 20:40:07 -07001260 // make the default display current because the VirtualDisplayDevice code cannot
1261 // deal with dequeueBuffer() being called outside of the composition loop; however
1262 // the code below can call glFlush() which is allowed (and does in some case) call
1263 // dequeueBuffer().
1264 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1265
Mathias Agopian92a979a2012-08-02 18:32:23 -07001266 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001267 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopian13127d82013-03-05 17:47:11 -08001268 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
Mathias Agopianda27af92012-09-13 18:17:13 -07001269 hw->onSwapBuffersCompleted(hwc);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001270 const size_t count = currentLayers.size();
Mathias Agopiane60b0682012-08-21 23:34:09 -07001271 int32_t id = hw->getHwcDisplayId();
1272 if (id >=0 && hwc.initCheck() == NO_ERROR) {
Mathias Agopian1e260872012-08-08 18:35:12 -07001273 HWComposer::LayerListIterator cur = hwc.begin(id);
1274 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001275 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001276 currentLayers[i]->onLayerDisplayed(hw, &*cur);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001277 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001278 } else {
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001279 for (size_t i = 0; i < count; i++) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001280 currentLayers[i]->onLayerDisplayed(hw, NULL);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001281 }
Jesse Hallef194142012-06-14 14:45:17 -07001282 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001283 }
1284
Mathias Agopiana44b0412011-10-16 18:46:35 -07001285 mLastSwapBufferTime = systemTime() - now;
1286 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001287
1288 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1289 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1290 logFrameStats();
1291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292}
1293
Mathias Agopian87baae12012-07-31 12:38:26 -07001294void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001295{
Mathias Agopian841cde52012-03-01 15:44:37 -08001296 ATRACE_CALL();
1297
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001298 // here we keep a copy of the drawing state (that is the state that's
1299 // going to be overwritten by handleTransactionLocked()) outside of
1300 // mStateLock so that the side-effects of the State assignment
1301 // don't happen with mStateLock held (which can cause deadlocks).
1302 State drawingState(mDrawingState);
1303
Mathias Agopianca4d3602011-05-19 15:38:14 -07001304 Mutex::Autolock _l(mStateLock);
1305 const nsecs_t now = systemTime();
1306 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001307
Mathias Agopianca4d3602011-05-19 15:38:14 -07001308 // Here we're guaranteed that some transaction flags are set
1309 // so we can call handleTransactionLocked() unconditionally.
1310 // We call getTransactionFlags(), which will also clear the flags,
1311 // with mStateLock held to guarantee that mCurrentState won't change
1312 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001313
Mathias Agopiane57f2922012-08-09 16:29:12 -07001314 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001315 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001316
Mathias Agopianca4d3602011-05-19 15:38:14 -07001317 mLastTransactionTime = systemTime() - now;
1318 mDebugInTransaction = 0;
1319 invalidateHwcGeometry();
1320 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001321}
1322
Mathias Agopian87baae12012-07-31 12:38:26 -07001323void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001324{
1325 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001326 const size_t count = currentLayers.size();
1327
Dan Stoza7dde5992015-05-22 09:51:44 -07001328 // Notify all layers of available frames
1329 for (size_t i = 0; i < count; ++i) {
1330 currentLayers[i]->notifyAvailableFrames();
1331 }
1332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001333 /*
1334 * Traversal of the children
1335 * (perform the transaction for each of them if needed)
1336 */
1337
Mathias Agopian3559b072012-08-15 13:46:03 -07001338 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001339 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001340 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1342 if (!trFlags) continue;
1343
1344 const uint32_t flags = layer->doTransaction(0);
1345 if (flags & Layer::eVisibleRegion)
1346 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001347 }
1348 }
1349
1350 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001351 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001352 */
1353
Mathias Agopiane57f2922012-08-09 16:29:12 -07001354 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001355 // here we take advantage of Vector's copy-on-write semantics to
1356 // improve performance by skipping the transaction entirely when
1357 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001358 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1359 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001360 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001361 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001362 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001363 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001364
1365 // find the displays that were removed
1366 // (ie: in drawing state but not in current state)
1367 // also handle displays that changed
1368 // (ie: displays that are in both lists)
1369 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001370 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1371 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001372 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001373 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001374 // Call makeCurrent() on the primary display so we can
1375 // be sure that nothing associated with this display
1376 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001377 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001378 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001379 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1380 if (hw != NULL)
1381 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001382 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001383 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001384 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001385 } else {
1386 ALOGW("trying to remove the main display");
1387 }
1388 } else {
1389 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001390 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001391 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001392 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1393 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001394 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001395 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001396 // recreating the DisplayDevice, so we just remove it
1397 // from the drawing state, so that it get re-added
1398 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001399 sp<DisplayDevice> hw(getDisplayDevice(display));
1400 if (hw != NULL)
1401 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001402 mDisplays.removeItem(display);
1403 mDrawingState.displays.removeItemsAt(i);
1404 dc--; i--;
1405 // at this point we must loop to the next item
1406 continue;
1407 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001408
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001409 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001410 if (disp != NULL) {
1411 if (state.layerStack != draw[i].layerStack) {
1412 disp->setLayerStack(state.layerStack);
1413 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001414 if ((state.orientation != draw[i].orientation)
1415 || (state.viewport != draw[i].viewport)
1416 || (state.frame != draw[i].frame))
1417 {
1418 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001419 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001420 }
Michael Lentine47e45402014-07-18 15:34:25 -07001421 if (state.width != draw[i].width || state.height != draw[i].height) {
1422 disp->setDisplaySize(state.width, state.height);
1423 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001424 }
1425 }
1426 }
1427
1428 // find displays that were added
1429 // (ie: in current state but not in drawing state)
1430 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001431 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001432 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001433
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001434 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001435 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001436 sp<IGraphicBufferProducer> bqProducer;
1437 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stozaacd56152016-01-08 09:36:21 -08001438 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001439
Jesse Hall02d86562013-03-25 14:43:23 -07001440 int32_t hwcDisplayId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001441 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001442 // Virtual displays without a surface are dormant:
1443 // they have external state (layer stack, projection,
1444 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001445 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001446
Dan Stoza1f3efb12014-10-15 16:34:55 -07001447 int width = 0;
1448 int status = state.surface->query(
1449 NATIVE_WINDOW_WIDTH, &width);
1450 ALOGE_IF(status != NO_ERROR,
1451 "Unable to query width (%d)", status);
1452 int height = 0;
1453 status = state.surface->query(
1454 NATIVE_WINDOW_HEIGHT, &height);
1455 ALOGE_IF(status != NO_ERROR,
1456 "Unable to query height (%d)", status);
1457 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1458 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1459 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1460 hwcDisplayId = allocateHwcDisplayId(state.type);
1461 }
1462
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001463 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
Dan Stozab9b08832014-03-13 11:55:57 -07001464 *mHwc, hwcDisplayId, state.surface,
1465 bqProducer, bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001466
1467 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001468 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001469 }
1470 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001471 ALOGE_IF(state.surface!=NULL,
1472 "adding a supported display, but rendering "
1473 "surface is provided (%p), ignoring it",
1474 state.surface.get());
Jesse Hall02d86562013-03-25 14:43:23 -07001475 hwcDisplayId = allocateHwcDisplayId(state.type);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001476 // for supported (by hwc) displays we provide our
1477 // own rendering surface
Dan Stozab9b08832014-03-13 11:55:57 -07001478 dispSurface = new FramebufferSurface(*mHwc, state.type,
1479 bqConsumer);
1480 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001481 }
1482
1483 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001484 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001485 sp<DisplayDevice> hw = new DisplayDevice(this,
Jesse Hall19e87292013-12-23 21:02:15 -08001486 state.type, hwcDisplayId,
1487 mHwc->getFormat(hwcDisplayId), state.isSecure,
Jesse Hall05f8c702013-12-23 20:44:38 -08001488 display, dispSurface, producer,
1489 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001490 hw->setLayerStack(state.layerStack);
1491 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001492 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001493 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001494 mDisplays.add(display, hw);
Jesse Hall1c569c42013-04-05 13:44:52 -07001495 if (state.isVirtualDisplay()) {
1496 if (hwcDisplayId >= 0) {
1497 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1498 hw->getWidth(), hw->getHeight(),
1499 hw->getFormat());
1500 }
1501 } else {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001502 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001503 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001504 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001505 }
1506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001507 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509
Mathias Agopian84300952012-11-21 16:02:13 -08001510 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1511 // The transform hint might have changed for some layers
1512 // (either because a display has changed, or because a layer
1513 // as changed).
1514 //
1515 // Walk through all the layers in currentLayers,
1516 // and update their transform hint.
1517 //
1518 // If a layer is visible only on a single display, then that
1519 // display is used to calculate the hint, otherwise we use the
1520 // default display.
1521 //
1522 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1523 // the hint is set before we acquire a buffer from the surface texture.
1524 //
1525 // NOTE: layer transactions have taken place already, so we use their
1526 // drawing state. However, SurfaceFlinger's own transaction has not
1527 // happened yet, so we must use the current state layer list
1528 // (soon to become the drawing state list).
1529 //
1530 sp<const DisplayDevice> disp;
1531 uint32_t currentlayerStack = 0;
1532 for (size_t i=0; i<count; i++) {
1533 // NOTE: we rely on the fact that layers are sorted by
1534 // layerStack first (so we don't have to traverse the list
1535 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001536 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001537 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001538 if (i==0 || currentlayerStack != layerStack) {
1539 currentlayerStack = layerStack;
1540 // figure out if this layerstack is mirrored
1541 // (more than one display) if so, pick the default display,
1542 // if not, pick the only display it's on.
1543 disp.clear();
1544 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1545 sp<const DisplayDevice> hw(mDisplays[dpy]);
1546 if (hw->getLayerStack() == currentlayerStack) {
1547 if (disp == NULL) {
1548 disp = hw;
1549 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001550 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001551 break;
1552 }
1553 }
1554 }
1555 }
Chet Haase91d25932013-04-11 15:24:55 -07001556 if (disp == NULL) {
1557 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1558 // redraw after transform hint changes. See bug 8508397.
1559
1560 // could be null when this layer is using a layerStack
1561 // that is not visible on any display. Also can occur at
1562 // screen off/on times.
1563 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001564 }
Chet Haase91d25932013-04-11 15:24:55 -07001565 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001566 }
1567 }
1568
1569
Mathias Agopian3559b072012-08-15 13:46:03 -07001570 /*
1571 * Perform our own transaction if needed
1572 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001573
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001574 const LayerVector& layers(mDrawingState.layersSortedByZ);
1575 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001576 // layers have been added
1577 mVisibleRegionsDirty = true;
1578 }
1579
1580 // some layers might have been removed, so
1581 // we need to update the regions they're exposing.
1582 if (mLayersRemoved) {
1583 mLayersRemoved = false;
1584 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001585 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001586 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001588 if (currentLayers.indexOf(layer) < 0) {
1589 // this layer is not visible anymore
1590 // TODO: we could traverse the tree from front to back and
1591 // compute the actual visible region
1592 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001593 const Layer::State& s(layer->getDrawingState());
Mathias Agopian1501d542012-09-04 21:04:09 -07001594 Region visibleReg = s.transform.transform(
1595 Region(Rect(s.active.w, s.active.h)));
1596 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001598 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001599 }
1600
1601 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001602
1603 updateCursorAsync();
1604}
1605
1606void SurfaceFlinger::updateCursorAsync()
1607{
1608 HWComposer& hwc(getHwComposer());
1609 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1610 sp<const DisplayDevice> hw(mDisplays[dpy]);
1611 const int32_t id = hw->getHwcDisplayId();
1612 if (id < 0) {
1613 continue;
1614 }
1615 const Vector< sp<Layer> >& currentLayers(
1616 hw->getVisibleLayersSortedByZ());
1617 const size_t count = currentLayers.size();
1618 HWComposer::LayerListIterator cur = hwc.begin(id);
1619 const HWComposer::LayerListIterator end = hwc.end(id);
1620 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1621 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1622 continue;
1623 }
1624 const sp<Layer>& layer(currentLayers[i]);
1625 Rect cursorPos = layer->getPosition(hw);
1626 hwc.setCursorPositionAsync(id, cursorPos);
1627 break;
1628 }
1629 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001630}
1631
1632void SurfaceFlinger::commitTransaction()
1633{
1634 if (!mLayersPendingRemoval.isEmpty()) {
1635 // Notify removed layers now that they can't be drawn from
1636 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1637 mLayersPendingRemoval[i]->onRemoved();
1638 }
1639 mLayersPendingRemoval.clear();
1640 }
1641
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001642 // If this transaction is part of a window animation then the next frame
1643 // we composite should be considered an animation as well.
1644 mAnimCompositionPending = mAnimTransactionPending;
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001647 mTransactionPending = false;
1648 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001649 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001650}
1651
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001652void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001653 const LayerVector& currentLayers, uint32_t layerStack,
1654 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001655{
Mathias Agopian841cde52012-03-01 15:44:37 -08001656 ATRACE_CALL();
1657
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001658 Region aboveOpaqueLayers;
1659 Region aboveCoveredLayers;
1660 Region dirty;
1661
Mathias Agopian87baae12012-07-31 12:38:26 -07001662 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001663
1664 size_t i = currentLayers.size();
1665 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001666 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001667
1668 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001669 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001670
Jesse Hall01e29052013-02-19 16:13:35 -08001671 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001672 if (s.layerStack != layerStack)
1673 continue;
1674
Mathias Agopianab028732010-03-16 16:41:46 -07001675 /*
1676 * opaqueRegion: area of a surface that is fully opaque.
1677 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001678 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001679
1680 /*
1681 * visibleRegion: area of a surface that is visible on screen
1682 * and not fully transparent. This is essentially the layer's
1683 * footprint minus the opaque regions above it.
1684 * Areas covered by a translucent surface are considered visible.
1685 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001686 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001687
1688 /*
1689 * coveredRegion: area of a surface that is covered by all
1690 * visible regions above it (which includes the translucent areas).
1691 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001692 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001693
Jesse Halla8026d22012-09-25 13:25:04 -07001694 /*
1695 * transparentRegion: area of a surface that is hinted to be completely
1696 * transparent. This is only used to tell when the layer has no visible
1697 * non-transparent regions and can be removed from the layer list. It
1698 * does not affect the visibleRegion of this layer or any layers
1699 * beneath it. The hint may not be correct if apps don't respect the
1700 * SurfaceView restrictions (which, sadly, some don't).
1701 */
1702 Region transparentRegion;
1703
Mathias Agopianab028732010-03-16 16:41:46 -07001704
1705 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001706 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001707 const bool translucent = !layer->isOpaque(s);
Mathias Agopian5219a062013-02-26 16:37:53 -08001708 Rect bounds(s.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001710 if (!visibleRegion.isEmpty()) {
1711 // Remove the transparent area from the visible region
1712 if (translucent) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713 const Transform tr(s.transform);
1714 if (tr.transformed()) {
1715 if (tr.preserveRects()) {
1716 // transform the transparent region
Mathias Agopian2ca79392013-04-02 18:30:32 -07001717 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001718 } else {
1719 // transformation too complex, can't do the
1720 // transparent region optimization.
Jesse Halla8026d22012-09-25 13:25:04 -07001721 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001722 }
1723 } else {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001724 transparentRegion = s.activeTransparentRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725 }
Mathias Agopianab028732010-03-16 16:41:46 -07001726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001727
Mathias Agopianab028732010-03-16 16:41:46 -07001728 // compute the opaque region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729 const int32_t layerOrientation = s.transform.getOrientation();
Mathias Agopianab028732010-03-16 16:41:46 -07001730 if (s.alpha==255 && !translucent &&
1731 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1732 // the opaque region is the layer's footprint
1733 opaqueRegion = visibleRegion;
1734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001735 }
1736 }
1737
Mathias Agopianab028732010-03-16 16:41:46 -07001738 // Clip the covered region to the visible region
1739 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1740
1741 // Update aboveCoveredLayers for next (lower) layer
1742 aboveCoveredLayers.orSelf(visibleRegion);
1743
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001744 // subtract the opaque region covered by the layers above us
1745 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001746
1747 // compute this layer's dirty region
1748 if (layer->contentDirty) {
1749 // we need to invalidate the whole region
1750 dirty = visibleRegion;
1751 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001752 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001753 layer->contentDirty = false;
1754 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001755 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001756 * the exposed region consists of two components:
1757 * 1) what's VISIBLE now and was COVERED before
1758 * 2) what's EXPOSED now less what was EXPOSED before
1759 *
1760 * note that (1) is conservative, we start with the whole
1761 * visible region but only keep what used to be covered by
1762 * something -- which mean it may have been exposed.
1763 *
1764 * (2) handles areas that were not covered by anything but got
1765 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001766 */
Mathias Agopianab028732010-03-16 16:41:46 -07001767 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001768 const Region oldVisibleRegion = layer->visibleRegion;
1769 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001770 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1771 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001772 }
1773 dirty.subtractSelf(aboveOpaqueLayers);
1774
1775 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001776 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777
Mathias Agopianab028732010-03-16 16:41:46 -07001778 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001780
Jesse Halla8026d22012-09-25 13:25:04 -07001781 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001782 layer->setVisibleRegion(visibleRegion);
1783 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001784 layer->setVisibleNonTransparentRegion(
1785 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 }
1787
Mathias Agopian87baae12012-07-31 12:38:26 -07001788 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001789}
1790
Mathias Agopian87baae12012-07-31 12:38:26 -07001791void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1792 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001793 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001794 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1795 if (hw->getLayerStack() == layerStack) {
1796 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001797 }
1798 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001799}
1800
Dan Stoza6b9454d2014-11-07 16:00:59 -08001801bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802{
Mathias Agopian4fec8732012-06-29 14:12:52 -07001803 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804
Mathias Agopian4fec8732012-06-29 14:12:52 -07001805 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001806 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001807 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001808
1809 // Store the set of layers that need updates. This set must not change as
1810 // buffers are being latched, as this could result in a deadlock.
1811 // Example: Two producers share the same command stream and:
1812 // 1.) Layer 0 is latched
1813 // 2.) Layer 0 gets a new frame
1814 // 2.) Layer 1 gets a new frame
1815 // 3.) Layer 1 is latched.
1816 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1817 // second frame. But layer 0's second frame could be waiting on display.
1818 Vector<Layer*> layersWithQueuedFrames;
1819 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001820 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001821 if (layer->hasQueuedFrame()) {
1822 frameQueued = true;
1823 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1824 layersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001825 } else {
1826 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001827 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001828 } else {
1829 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001830 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001831 }
1832 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1833 Layer* layer = layersWithQueuedFrames[i];
Mathias Agopian87baae12012-07-31 12:38:26 -07001834 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001835 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001836 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001837 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001838 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001839
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001840 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001841
1842 // If we will need to wake up at some time in the future to deal with a
1843 // queued frame that shouldn't be displayed during this vsync period, wake
1844 // up during the next vsync period to check again.
1845 if (frameQueued && layersWithQueuedFrames.empty()) {
1846 signalLayerUpdate();
1847 }
1848
1849 // Only continue with the refresh if there is actually new work to do
1850 return !layersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001851}
1852
Mathias Agopianad456f92011-01-13 17:53:01 -08001853void SurfaceFlinger::invalidateHwcGeometry()
1854{
1855 mHwWorkListDirty = true;
1856}
1857
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001858
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001860 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001861{
Dan Stoza71433162014-02-04 16:22:36 -08001862 // We only need to actually compose the display if:
1863 // 1) It is being handled by hardware composer, which may need this to
1864 // keep its virtual display state machine in sync, or
1865 // 2) There is work to be done (the dirty region isn't empty)
1866 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1867 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1868 return;
1869 }
1870
Mathias Agopian87baae12012-07-31 12:38:26 -07001871 Region dirtyRegion(inDirtyRegion);
1872
Mathias Agopianb8a55602009-06-26 19:06:36 -07001873 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001874 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875
Mathias Agopian42977342012-08-05 00:40:46 -07001876 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001877 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001878 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1879 // takes a rectangle, we must make sure to update that whole
1880 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001881 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001882 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001883 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001884 // We need to redraw the rectangle that will be updated
1885 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001886 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001887 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001888 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001889 } else {
1890 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001891 dirtyRegion.set(hw->bounds());
1892 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 }
1894 }
1895
Alan Viverette9c5a3332013-09-12 20:04:35 -07001896 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001897 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001898 } else {
1899 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001900 mat4 colorMatrix = mColorMatrix;
1901 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001902 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001903 }
Dan Stozaf0087992014-10-20 15:46:09 -07001904 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001905 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001906 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001909 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001910 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001911
1912 // swap buffers (presentation)
1913 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001914}
1915
Michael Lentine3f121fc2014-10-01 11:17:28 -07001916bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001917{
Mathias Agopian3f844832013-08-07 21:24:32 -07001918 RenderEngine& engine(getRenderEngine());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001919 const int32_t id = hw->getHwcDisplayId();
Mathias Agopian86303202012-07-24 22:46:10 -07001920 HWComposer& hwc(getHwComposer());
Mathias Agopian1e260872012-08-08 18:35:12 -07001921 HWComposer::LayerListIterator cur = hwc.begin(id);
1922 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001923
Jesse Halld05a17f2013-09-30 16:49:30 -07001924 bool hasGlesComposition = hwc.hasGlesComposition(id);
Mathias Agopian85d751c2012-08-29 16:59:24 -07001925 if (hasGlesComposition) {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001926 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001927 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1928 hw->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001929 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1930 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1931 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1932 }
1933 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001934 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001935
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001936 // Never touch the framebuffer if we don't have any framebuffer layers
Mathias Agopian85d751c2012-08-29 16:59:24 -07001937 const bool hasHwcComposition = hwc.hasHwcComposition(id);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001938 if (hasHwcComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001939 // when using overlays, we assume a fully transparent framebuffer
1940 // NOTE: we could reduce how much we need to clear, for instance
1941 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001942 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001943 // We'll revisit later if needed.
Mathias Agopian3f844832013-08-07 21:24:32 -07001944 engine.clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001945 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001946 // we start with the whole screen area
1947 const Region bounds(hw->getBounds());
1948
1949 // we remove the scissor part
1950 // we're left with the letterbox region
1951 // (common case is that letterbox ends-up being empty)
1952 const Region letterbox(bounds.subtract(hw->getScissor()));
1953
1954 // compute the area to clear
1955 Region region(hw->undefinedRegion.merge(letterbox));
1956
1957 // but limit it to the dirty region
1958 region.andSelf(dirty);
1959
Mathias Agopianb9494d52012-04-18 02:28:45 -07001960 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001961 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001962 // can happen with SurfaceView
Mathias Agopian55801e42012-08-27 18:54:24 -07001963 drawWormhole(hw, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001964 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001965 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001966
Mathias Agopian766dc492012-10-30 18:08:06 -07001967 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1968 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001969 // scissor on the main display. It should never be needed
1970 // anyways (though in theory it could since the API allows it).
1971 const Rect& bounds(hw->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001972 const Rect& scissor(hw->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001973 if (scissor != bounds) {
1974 // scissor doesn't match the screen's dimensions, so we
1975 // need to clear everything outside of it and enable
1976 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001977
Mathias Agopianf45c5102012-10-24 16:29:17 -07001978 // enable scissor for this frame
Mathias Agopian3f844832013-08-07 21:24:32 -07001979 const uint32_t height = hw->getHeight();
1980 engine.setScissor(scissor.left, height - scissor.bottom,
1981 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001982 }
1983 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001984 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001985
Mathias Agopian85d751c2012-08-29 16:59:24 -07001986 /*
1987 * and then, render the layers targeted at the framebuffer
1988 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001989
Mathias Agopian13127d82013-03-05 17:47:11 -08001990 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001991 const size_t count = layers.size();
1992 const Transform& tr = hw->getTransform();
1993 if (cur != end) {
1994 // we're using h/w composer
1995 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001996 const sp<Layer>& layer(layers[i]);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001997 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07001998 if (!clip.isEmpty()) {
1999 switch (cur->getCompositionType()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002000 case HWC_CURSOR_OVERLAY:
Mathias Agopian85d751c2012-08-29 16:59:24 -07002001 case HWC_OVERLAY: {
Mathias Agopianac683022013-10-01 15:36:52 -07002002 const Layer::State& state(layer->getDrawingState());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002003 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2004 && i
Andy McFadden4125a4f2014-01-29 17:17:11 -08002005 && layer->isOpaque(state) && (state.alpha == 0xFF)
Mathias Agopian85d751c2012-08-29 16:59:24 -07002006 && hasGlesComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007 // never clear the very first layer since we're
2008 // guaranteed the FB is already cleared
2009 layer->clearWithOpenGL(hw, clip);
2010 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002011 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002013 case HWC_FRAMEBUFFER: {
2014 layer->draw(hw, clip);
2015 break;
2016 }
Mathias Agopianda27af92012-09-13 18:17:13 -07002017 case HWC_FRAMEBUFFER_TARGET: {
2018 // this should not happen as the iterator shouldn't
2019 // let us get there.
Greg Hackmann86efcc02014-03-07 12:44:02 -08002020 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
Mathias Agopianda27af92012-09-13 18:17:13 -07002021 break;
2022 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002024 }
2025 layer->setAcquireFence(hw, *cur);
2026 }
2027 } else {
2028 // we're not using h/w composer
2029 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002030 const sp<Layer>& layer(layers[i]);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002031 const Region clip(dirty.intersect(
2032 tr.transform(layer->visibleRegion)));
2033 if (!clip.isEmpty()) {
2034 layer->draw(hw, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002035 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002036 }
2037 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002038
2039 // disable scissor at the end of the frame
Mathias Agopian3f844832013-08-07 21:24:32 -07002040 engine.disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002041 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042}
2043
Mathias Agopian3f844832013-08-07 21:24:32 -07002044void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002045 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002046 RenderEngine& engine(getRenderEngine());
2047 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002048}
2049
Dan Stoza7d89d062015-04-30 13:29:25 -07002050status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002051 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002052 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002053 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002054{
Dan Stoza7d89d062015-04-30 13:29:25 -07002055 // add this layer to the current state list
2056 {
2057 Mutex::Autolock _l(mStateLock);
2058 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2059 return NO_MEMORY;
2060 }
2061 mCurrentState.layersSortedByZ.add(lbc);
2062 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2063 }
2064
Mathias Agopian96f08192010-06-02 23:28:45 -07002065 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002066 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002067
Dan Stoza7d89d062015-04-30 13:29:25 -07002068 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002069}
2070
Mathias Agopian3f844832013-08-07 21:24:32 -07002071status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002073 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002075 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002076 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002077 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078 return NO_ERROR;
2079 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002080 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081}
2082
Dan Stozac7014012014-02-14 15:03:43 -08002083uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002084 return android_atomic_release_load(&mTransactionFlags);
2085}
2086
Mathias Agopian3f844832013-08-07 21:24:32 -07002087uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2089}
2090
Mathias Agopian3f844832013-08-07 21:24:32 -07002091uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002092 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2093 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002094 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 }
2096 return old;
2097}
2098
Mathias Agopian8b33f032012-07-24 20:43:54 -07002099void SurfaceFlinger::setTransactionState(
2100 const Vector<ComposerState>& state,
2101 const Vector<DisplayState>& displays,
2102 uint32_t flags)
2103{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002104 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002105 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002106 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002107
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002108 if (flags & eAnimation) {
2109 // For window updates that are part of an animation we must wait for
2110 // previous animation "frames" to be handled.
2111 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002112 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002113 if (CC_UNLIKELY(err != NO_ERROR)) {
2114 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002115 // caller after a few seconds.
2116 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2117 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002118 mAnimTransactionPending = false;
2119 break;
2120 }
2121 }
2122 }
2123
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124 size_t count = displays.size();
2125 for (size_t i=0 ; i<count ; i++) {
2126 const DisplayState& s(displays[i]);
2127 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002128 }
2129
Mathias Agopiane57f2922012-08-09 16:29:12 -07002130 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002131 for (size_t i=0 ; i<count ; i++) {
2132 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002133 // Here we need to check that the interface we're given is indeed
2134 // one of our own. A malicious client could give us a NULL
2135 // IInterface, or one of its own or even one of our own but a
2136 // different type. All these situations would cause us to crash.
2137 //
2138 // NOTE: it would be better to use RTTI as we could directly check
2139 // that we have a Client*. however, RTTI is disabled in Android.
2140 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002141 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002142 if (binder != NULL) {
2143 String16 desc(binder->getInterfaceDescriptor());
2144 if (desc == ISurfaceComposerClient::descriptor) {
2145 sp<Client> client( static_cast<Client *>(s.client.get()) );
2146 transactionFlags |= setClientStateLocked(client, s.state);
2147 }
2148 }
2149 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002150 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002151
Mathias Agopian386aa982011-11-07 21:58:03 -08002152 if (transactionFlags) {
2153 // this triggers the transaction
2154 setTransactionFlags(transactionFlags);
2155
2156 // if this is a synchronous transaction, wait for it to take effect
2157 // before returning.
2158 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002159 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002160 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002161 if (flags & eAnimation) {
2162 mAnimTransactionPending = true;
2163 }
2164 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002165 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2166 if (CC_UNLIKELY(err != NO_ERROR)) {
2167 // just in case something goes wrong in SF, return to the
2168 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002169 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2170 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002171 break;
2172 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174 }
2175}
2176
Mathias Agopiane57f2922012-08-09 16:29:12 -07002177uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2178{
Jesse Hall9a143922012-10-04 16:29:19 -07002179 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2180 if (dpyIdx < 0)
2181 return 0;
2182
Mathias Agopiane57f2922012-08-09 16:29:12 -07002183 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002184 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002185 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002186 const uint32_t what = s.what;
2187 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002188 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002189 disp.surface = s.surface;
2190 flags |= eDisplayTransactionNeeded;
2191 }
2192 }
2193 if (what & DisplayState::eLayerStackChanged) {
2194 if (disp.layerStack != s.layerStack) {
2195 disp.layerStack = s.layerStack;
2196 flags |= eDisplayTransactionNeeded;
2197 }
2198 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002199 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002200 if (disp.orientation != s.orientation) {
2201 disp.orientation = s.orientation;
2202 flags |= eDisplayTransactionNeeded;
2203 }
2204 if (disp.frame != s.frame) {
2205 disp.frame = s.frame;
2206 flags |= eDisplayTransactionNeeded;
2207 }
2208 if (disp.viewport != s.viewport) {
2209 disp.viewport = s.viewport;
2210 flags |= eDisplayTransactionNeeded;
2211 }
2212 }
Michael Lentine47e45402014-07-18 15:34:25 -07002213 if (what & DisplayState::eDisplaySizeChanged) {
2214 if (disp.width != s.width) {
2215 disp.width = s.width;
2216 flags |= eDisplayTransactionNeeded;
2217 }
2218 if (disp.height != s.height) {
2219 disp.height = s.height;
2220 flags |= eDisplayTransactionNeeded;
2221 }
2222 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002223 }
2224 return flags;
2225}
2226
2227uint32_t SurfaceFlinger::setClientStateLocked(
2228 const sp<Client>& client,
2229 const layer_state_t& s)
2230{
2231 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002232 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002233 if (layer != 0) {
2234 const uint32_t what = s.what;
2235 if (what & layer_state_t::ePositionChanged) {
2236 if (layer->setPosition(s.x, s.y))
2237 flags |= eTraversalNeeded;
2238 }
2239 if (what & layer_state_t::eLayerChanged) {
2240 // NOTE: index needs to be calculated before we update the state
2241 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002242 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 mCurrentState.layersSortedByZ.removeAt(idx);
2244 mCurrentState.layersSortedByZ.add(layer);
2245 // we need traversal (state changed)
2246 // AND transaction (list changed)
2247 flags |= eTransactionNeeded|eTraversalNeeded;
2248 }
2249 }
2250 if (what & layer_state_t::eSizeChanged) {
2251 if (layer->setSize(s.w, s.h)) {
2252 flags |= eTraversalNeeded;
2253 }
2254 }
2255 if (what & layer_state_t::eAlphaChanged) {
2256 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2257 flags |= eTraversalNeeded;
2258 }
2259 if (what & layer_state_t::eMatrixChanged) {
2260 if (layer->setMatrix(s.matrix))
2261 flags |= eTraversalNeeded;
2262 }
2263 if (what & layer_state_t::eTransparentRegionChanged) {
2264 if (layer->setTransparentRegionHint(s.transparentRegion))
2265 flags |= eTraversalNeeded;
2266 }
Dan Stoza23116082015-06-18 14:58:39 -07002267 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002268 if (layer->setFlags(s.flags, s.mask))
2269 flags |= eTraversalNeeded;
2270 }
2271 if (what & layer_state_t::eCropChanged) {
2272 if (layer->setCrop(s.crop))
2273 flags |= eTraversalNeeded;
2274 }
2275 if (what & layer_state_t::eLayerStackChanged) {
2276 // NOTE: index needs to be calculated before we update the state
2277 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002278 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002279 mCurrentState.layersSortedByZ.removeAt(idx);
2280 mCurrentState.layersSortedByZ.add(layer);
2281 // we need traversal (state changed)
2282 // AND transaction (list changed)
2283 flags |= eTransactionNeeded|eTraversalNeeded;
2284 }
2285 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002286 if (what & layer_state_t::eDeferTransaction) {
2287 layer->deferTransactionUntil(s.handle, s.frameNumber);
2288 // We don't trigger a traversal here because if no other state is
2289 // changed, we don't want this to cause any more work
2290 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002291 }
2292 return flags;
2293}
2294
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002295status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002296 const String8& name,
2297 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002298 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2299 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002301 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002302 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002303 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002304 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002305 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002306 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002307
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002308 status_t result = NO_ERROR;
2309
2310 sp<Layer> layer;
2311
Mathias Agopian3165cc22012-08-08 19:42:09 -07002312 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2313 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002314 result = createNormalLayer(client,
2315 name, w, h, flags, format,
2316 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002318 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002319 result = createDimLayer(client,
2320 name, w, h, flags,
2321 handle, gbp, &layer);
2322 break;
2323 default:
2324 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325 break;
2326 }
2327
Dan Stoza7d89d062015-04-30 13:29:25 -07002328 if (result != NO_ERROR) {
2329 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002331
2332 result = addClientLayer(client, *handle, *gbp, layer);
2333 if (result != NO_ERROR) {
2334 return result;
2335 }
2336
2337 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002338 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339}
2340
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002341status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2342 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2343 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344{
2345 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002346 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 case PIXEL_FORMAT_TRANSPARENT:
2348 case PIXEL_FORMAT_TRANSLUCENT:
2349 format = PIXEL_FORMAT_RGBA_8888;
2350 break;
2351 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002352 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353 break;
2354 }
2355
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002356 *outLayer = new Layer(this, client, name, w, h, flags);
2357 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2358 if (err == NO_ERROR) {
2359 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002360 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002362
2363 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2364 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365}
2366
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002367status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2368 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2369 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002371 *outLayer = new LayerDim(this, client, name, w, h, flags);
2372 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002373 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002374 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002375}
2376
Mathias Agopianac9fa422013-02-11 16:40:36 -08002377status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378{
Mathias Agopian67106042013-03-14 19:18:13 -07002379 // called by the window manager when it wants to remove a Layer
2380 status_t err = NO_ERROR;
2381 sp<Layer> l(client->getLayerUser(handle));
2382 if (l != NULL) {
2383 err = removeLayer(l);
2384 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2385 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002386 }
2387 return err;
2388}
2389
Mathias Agopian13127d82013-03-05 17:47:11 -08002390status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002391{
Mathias Agopian67106042013-03-14 19:18:13 -07002392 // called by ~LayerCleaner() when all references to the IBinder (handle)
2393 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002394 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002395 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002396 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002397 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002398 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002399 "error removing layer=%p (%s)", l.get(), strerror(-err));
2400 }
2401 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402}
2403
Mathias Agopianb60314a2012-04-10 22:09:54 -07002404// ---------------------------------------------------------------------------
2405
Andy McFadden13a082e2012-08-24 10:16:42 -07002406void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002407 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002408 Vector<ComposerState> state;
2409 Vector<DisplayState> displays;
2410 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002411 d.what = DisplayState::eDisplayProjectionChanged |
2412 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002413 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002414 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002415 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002416 d.frame.makeInvalid();
2417 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002418 d.width = 0;
2419 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002420 displays.add(d);
2421 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002422 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002423
2424 const nsecs_t period =
2425 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2426 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002427}
2428
2429void SurfaceFlinger::initializeDisplays() {
2430 class MessageScreenInitialized : public MessageBase {
2431 SurfaceFlinger* flinger;
2432 public:
2433 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2434 virtual bool handler() {
2435 flinger->onInitializeDisplays();
2436 return true;
2437 }
2438 };
2439 sp<MessageBase> msg = new MessageScreenInitialized(this);
2440 postMessageAsync(msg); // we may be called from main thread, use async message
2441}
2442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002443void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2444 int mode) {
2445 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2446 this);
2447 int32_t type = hw->getDisplayType();
2448 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002449
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002450 if (mode == currentMode) {
2451 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002452 return;
2453 }
2454
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002455 hw->setPowerMode(mode);
2456 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2457 ALOGW("Trying to set power mode for virtual display");
2458 return;
2459 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002460
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002461 if (currentMode == HWC_POWER_MODE_OFF) {
2462 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002463 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2464 // FIXME: eventthread only knows about the main display right now
2465 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002466 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002469 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002470 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002471 repaintEverything();
2472 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002473 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002474 disableHardwareVsync(true); // also cancels any in-progress resync
2475
Mathias Agopiancde87a32012-09-13 14:09:01 -07002476 // FIXME: eventthread only knows about the main display right now
2477 mEventThread->onScreenReleased();
2478 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002479
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002480 getHwComposer().setPowerMode(type, mode);
2481 mVisibleRegionsDirty = true;
2482 // from this point on, SF will stop drawing on this display
2483 } else {
2484 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002485 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002486}
2487
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002488void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2489 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002490 SurfaceFlinger& mFlinger;
2491 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002492 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002493 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002494 MessageSetPowerMode(SurfaceFlinger& flinger,
2495 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2496 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002497 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002498 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002499 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002500 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002501 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002502 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002503 ALOGW("Attempt to set power mode = %d for virtual display",
2504 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002505 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002506 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002507 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002508 return true;
2509 }
2510 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002511 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002512 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002513}
2514
2515// ---------------------------------------------------------------------------
2516
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2518{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002520
Mathias Agopianbd115332013-04-18 16:41:04 -07002521 IPCThreadState* ipc = IPCThreadState::self();
2522 const int pid = ipc->getCallingPid();
2523 const int uid = ipc->getCallingUid();
2524 if ((uid != AID_SHELL) &&
2525 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002526 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002527 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002529 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002530 // (this would indicate SF is stuck, but we want to be able to
2531 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002532 status_t err = mStateLock.timedLock(s2ns(1));
2533 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002534 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002535 result.appendFormat(
2536 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2537 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002538 }
2539
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002540 bool dumpAll = true;
2541 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002542 size_t numArgs = args.size();
2543 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002544 if ((index < numArgs) &&
2545 (args[index] == String16("--list"))) {
2546 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002547 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002548 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002549 }
2550
2551 if ((index < numArgs) &&
2552 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002553 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002554 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002555 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002556 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002557
2558 if ((index < numArgs) &&
2559 (args[index] == String16("--latency-clear"))) {
2560 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002561 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002562 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002563 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002564
2565 if ((index < numArgs) &&
2566 (args[index] == String16("--dispsync"))) {
2567 index++;
2568 mPrimaryDispSync.dump(result);
2569 dumpAll = false;
2570 }
Dan Stozab90cf072015-03-05 11:05:59 -08002571
2572 if ((index < numArgs) &&
2573 (args[index] == String16("--static-screen"))) {
2574 index++;
2575 dumpStaticScreenStats(result);
2576 dumpAll = false;
2577 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002579
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002580 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002581 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002582 }
2583
Mathias Agopian9795c422009-08-26 16:36:26 -07002584 if (locked) {
2585 mStateLock.unlock();
2586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588 write(fd, result.string(), result.size());
2589 return NO_ERROR;
2590}
2591
Dan Stozac7014012014-02-14 15:03:43 -08002592void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2593 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002594{
2595 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2596 const size_t count = currentLayers.size();
2597 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002598 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002599 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002600 }
2601}
2602
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002603void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002604 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002605{
2606 String8 name;
2607 if (index < args.size()) {
2608 name = String8(args[index]);
2609 index++;
2610 }
2611
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002612 const nsecs_t period =
2613 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002614 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002615
2616 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002617 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002618 } else {
2619 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2620 const size_t count = currentLayers.size();
2621 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002622 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002623 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002624 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002625 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002626 }
2627 }
2628}
2629
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002630void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002631 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002632{
2633 String8 name;
2634 if (index < args.size()) {
2635 name = String8(args[index]);
2636 index++;
2637 }
2638
2639 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2640 const size_t count = currentLayers.size();
2641 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002642 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002643 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002644 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002645 }
2646 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002647
Svetoslavd85084b2014-03-20 10:28:31 -07002648 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002649}
2650
Jamie Gennis6547ff42013-07-16 20:12:42 -07002651// This should only be called from the main thread. Otherwise it would need
2652// the lock and should use mCurrentState rather than mDrawingState.
2653void SurfaceFlinger::logFrameStats() {
2654 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2655 const size_t count = drawingLayers.size();
2656 for (size_t i=0 ; i<count ; i++) {
2657 const sp<Layer>& layer(drawingLayers[i]);
2658 layer->logFrameStats();
2659 }
2660
2661 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2662}
2663
Andy McFadden4803b742012-09-24 19:07:20 -07002664/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2665{
2666 static const char* config =
2667 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002668#ifdef HAS_CONTEXT_PRIORITY
2669 " HAS_CONTEXT_PRIORITY"
2670#endif
2671#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2672 " NEVER_DEFAULT_TO_ASYNC_MODE"
2673#endif
2674#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2675 " TARGET_DISABLE_TRIPLE_BUFFERING"
2676#endif
2677 "]";
2678 result.append(config);
2679}
2680
Dan Stozab90cf072015-03-05 11:05:59 -08002681void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2682{
2683 result.appendFormat("Static screen stats:\n");
2684 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2685 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2686 float percent = 100.0f *
2687 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2688 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2689 b + 1, bucketTimeSec, percent);
2690 }
2691 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2692 float percent = 100.0f *
2693 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2694 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2695 NUM_BUCKETS - 1, bucketTimeSec, percent);
2696}
2697
Mathias Agopian74d211a2013-04-22 16:55:35 +02002698void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2699 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002700{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002701 bool colorize = false;
2702 if (index < args.size()
2703 && (args[index] == String16("--color"))) {
2704 colorize = true;
2705 index++;
2706 }
2707
2708 Colorizer colorizer(colorize);
2709
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002710 // figure out if we're stuck somewhere
2711 const nsecs_t now = systemTime();
2712 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2713 const nsecs_t inTransaction(mDebugInTransaction);
2714 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2715 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2716
2717 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002718 * Dump library configuration.
2719 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002720
2721 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002722 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002723 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002724 appendSfConfigString(result);
2725 appendUiConfigString(result);
2726 appendGuiConfigString(result);
2727 result.append("\n");
2728
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002729 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002730 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002731 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002732 result.append(SyncFeatures::getInstance().toString());
2733 result.append("\n");
2734
Andy McFadden41d67d72014-04-25 16:58:34 -07002735 colorizer.bold(result);
2736 result.append("DispSync configuration: ");
2737 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002738 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2739 "present offset %d ns (refresh %" PRId64 " ns)",
Andy McFadden41d67d72014-04-25 16:58:34 -07002740 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2741 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2742 result.append("\n");
2743
Dan Stozab90cf072015-03-05 11:05:59 -08002744 // Dump static screen stats
2745 result.append("\n");
2746 dumpStaticScreenStats(result);
2747 result.append("\n");
2748
Andy McFadden4803b742012-09-24 19:07:20 -07002749 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002750 * Dump the visible layer list
2751 */
2752 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2753 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002754 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002755 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002756 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002757 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002758 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002759 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002760 }
2761
2762 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002763 * Dump Display state
2764 */
2765
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002766 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002767 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002768 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002769 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2770 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002771 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002772 }
2773
2774 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002775 * Dump SurfaceFlinger global state
2776 */
2777
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002778 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002779 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002780 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002781
Mathias Agopian888c8222012-08-04 21:10:38 -07002782 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002783 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002784
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002785 colorizer.bold(result);
2786 result.appendFormat("EGL implementation : %s\n",
2787 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2788 colorizer.reset(result);
2789 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002790 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002791
Mathias Agopian875d8e12013-06-07 15:35:48 -07002792 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002793
Mathias Agopian42977342012-08-05 00:40:46 -07002794 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002795 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2796 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002797 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002798 " last eglSwapBuffers() time: %f us\n"
2799 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002800 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002801 " refresh-rate : %f fps\n"
2802 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002803 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002804 " gpu_to_cpu_unsupported : %d\n"
2805 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002806 mLastSwapBufferTime/1000.0,
2807 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002808 mTransactionFlags,
Andy McFaddenb0d1dd32012-09-10 14:08:09 -07002809 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2810 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002811 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002812 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002813
Mathias Agopian74d211a2013-04-22 16:55:35 +02002814 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002815 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002816
Mathias Agopian74d211a2013-04-22 16:55:35 +02002817 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002818 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002819
2820 /*
2821 * VSYNC state
2822 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002823 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002824
2825 /*
2826 * Dump HWComposer state
2827 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002828 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002829 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002830 colorizer.reset(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002831 result.appendFormat(" h/w composer %s and %s\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002832 hwc.initCheck()==NO_ERROR ? "present" : "not present",
Alan Viverette9c5a3332013-09-12 20:04:35 -07002833 (mDebugDisableHWC || mDebugRegion || mDaltonize
2834 || mHasColorMatrix) ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002835 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002836
2837 /*
2838 * Dump gralloc state
2839 */
2840 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2841 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002842}
2843
Mathias Agopian13127d82013-03-05 17:47:11 -08002844const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002845SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002846 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002847 wp<IBinder> dpy;
2848 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2849 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2850 dpy = mDisplays.keyAt(i);
2851 break;
2852 }
2853 }
2854 if (dpy == NULL) {
2855 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2856 // Just use the primary display so we have something to return
2857 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2858 }
2859 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002860}
2861
Keun young Park63f165f2012-08-31 10:53:36 -07002862bool SurfaceFlinger::startDdmConnection()
2863{
2864 void* libddmconnection_dso =
2865 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2866 if (!libddmconnection_dso) {
2867 return false;
2868 }
2869 void (*DdmConnection_start)(const char* name);
2870 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002871 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002872 if (!DdmConnection_start) {
2873 dlclose(libddmconnection_dso);
2874 return false;
2875 }
2876 (*DdmConnection_start)(getServiceName());
2877 return true;
2878}
2879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880status_t SurfaceFlinger::onTransact(
2881 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2882{
2883 switch (code) {
2884 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002885 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002886 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002888 case CLEAR_ANIMATION_FRAME_STATS:
2889 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002890 case SET_POWER_MODE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 {
2892 // codes that require permission check
2893 IPCThreadState* ipc = IPCThreadState::self();
2894 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002895 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002896 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002897 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002898 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002899 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2900 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002902 break;
2903 }
2904 case CAPTURE_SCREEN:
2905 {
2906 // codes that require permission check
2907 IPCThreadState* ipc = IPCThreadState::self();
2908 const int pid = ipc->getCallingPid();
2909 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002910 if ((uid != AID_GRAPHICS) &&
2911 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002912 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002913 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2914 return PERMISSION_DENIED;
2915 }
2916 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 }
2918 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2921 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002922 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002923 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002924 IPCThreadState* ipc = IPCThreadState::self();
2925 const int pid = ipc->getCallingPid();
2926 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002927 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002928 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 return PERMISSION_DENIED;
2930 }
2931 int n;
2932 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07002933 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07002934 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 return NO_ERROR;
2936 case 1002: // SHOW_UPDATES
2937 n = data.readInt32();
2938 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07002939 invalidateHwcGeometry();
2940 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07002943 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002944 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002946 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07002947 setTransactionFlags(
2948 eTransactionNeeded|
2949 eDisplayTransactionNeeded|
2950 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002951 return NO_ERROR;
2952 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002953 case 1006:{ // send empty update
2954 signalRefresh();
2955 return NO_ERROR;
2956 }
Mathias Agopian53331da2011-08-22 21:44:41 -07002957 case 1008: // toggle use of hw composer
2958 n = data.readInt32();
2959 mDebugDisableHWC = n ? 1 : 0;
2960 invalidateHwcGeometry();
2961 repaintEverything();
2962 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07002963 case 1009: // toggle use of transform hint
2964 n = data.readInt32();
2965 mDebugDisableTransformHint = n ? 1 : 0;
2966 invalidateHwcGeometry();
2967 repaintEverything();
2968 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07002970 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 reply->writeInt32(0);
2972 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002973 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08002974 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975 return NO_ERROR;
2976 case 1013: {
2977 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07002978 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2979 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07002980 return NO_ERROR;
2981 }
2982 case 1014: {
2983 // daltonize
2984 n = data.readInt32();
2985 switch (n % 10) {
2986 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2987 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2988 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2989 }
2990 if (n >= 10) {
2991 mDaltonizer.setMode(Daltonizer::correction);
2992 } else {
2993 mDaltonizer.setMode(Daltonizer::simulation);
2994 }
2995 mDaltonize = n > 0;
2996 invalidateHwcGeometry();
2997 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07002998 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003000 case 1015: {
3001 // apply a color matrix
3002 n = data.readInt32();
3003 mHasColorMatrix = n ? 1 : 0;
3004 if (n) {
3005 // color matrix is sent as mat3 matrix followed by vec3
3006 // offset, then packed into a mat4 where the last row is
3007 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003008 for (size_t i = 0 ; i < 4; i++) {
3009 for (size_t j = 0; j < 4; j++) {
3010 mColorMatrix[i][j] = data.readFloat();
3011 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003012 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003013 } else {
3014 mColorMatrix = mat4();
3015 }
3016 invalidateHwcGeometry();
3017 repaintEverything();
3018 return NO_ERROR;
3019 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003020 // This is an experimental interface
3021 // Needs to be shifted to proper binder interface when we productize
3022 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003023 n = data.readInt32();
3024 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003025 return NO_ERROR;
3026 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003027 case 1017: {
3028 n = data.readInt32();
3029 mForceFullDamage = static_cast<bool>(n);
3030 return NO_ERROR;
3031 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003032 case 1018: { // Modify Choreographer's phase offset
3033 n = data.readInt32();
3034 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3035 return NO_ERROR;
3036 }
3037 case 1019: { // Modify SurfaceFlinger's phase offset
3038 n = data.readInt32();
3039 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3040 return NO_ERROR;
3041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 }
3043 }
3044 return err;
3045}
3046
Mathias Agopian53331da2011-08-22 21:44:41 -07003047void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003048 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003049 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003050}
3051
Mathias Agopian59119e62010-10-11 12:37:43 -07003052// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003053// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003054// ---------------------------------------------------------------------------
3055
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003056/* The code below is here to handle b/8734824
3057 *
3058 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003059 * from the surfaceflinger thread to the calling binder thread, where they
3060 * are executed. This allows the calling thread in the calling process to be
3061 * reused and not depend on having "enough" binder threads to handle the
3062 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003063 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003064class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003065 /* Parts of GraphicProducerWrapper are run on two different threads,
3066 * communicating by sending messages via Looper but also by shared member
3067 * data. Coherence maintenance is subtle and in places implicit (ugh).
3068 *
3069 * Don't rely on Looper's sendMessage/handleMessage providing
3070 * release/acquire semantics for any data not actually in the Message.
3071 * Data going from surfaceflinger to binder threads needs to be
3072 * synchronized explicitly.
3073 *
3074 * Barrier open/wait do provide release/acquire semantics. This provides
3075 * implicit synchronization for data coming back from binder to
3076 * surfaceflinger threads.
3077 */
3078
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003079 sp<IGraphicBufferProducer> impl;
3080 sp<Looper> looper;
3081 status_t result;
3082 bool exitPending;
3083 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003084 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003085 uint32_t code;
3086 Parcel const* data;
3087 Parcel* reply;
3088
3089 enum {
3090 MSG_API_CALL,
3091 MSG_EXIT
3092 };
3093
3094 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003095 * Called on surfaceflinger thread. This is called by our "fake"
3096 * BpGraphicBufferProducer. We package the data and reply Parcel and
3097 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003098 */
3099 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003100 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003101 this->code = code;
3102 this->data = &data;
3103 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003104 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003105 // if we've exited, we run the message synchronously right here.
3106 // note (JH): as far as I can tell from looking at the code, this
3107 // never actually happens. if it does, i'm not sure if it happens
3108 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003109 handleMessage(Message(MSG_API_CALL));
3110 } else {
3111 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003112 // Prevent stores to this->{code, data, reply} from being
3113 // reordered later than the construction of Message.
3114 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003115 looper->sendMessage(this, Message(MSG_API_CALL));
3116 barrier.wait();
3117 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003118 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003119 }
3120
3121 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003122 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003123 * call the real BpGraphicBufferProducer.
3124 */
3125 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003126 int what = message.what;
3127 // Prevent reads below from happening before the read from Message
3128 atomic_thread_fence(memory_order_acquire);
3129 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003130 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003131 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003132 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003133 exitRequested = true;
3134 }
3135 }
3136
3137public:
Jesse Hallb154c422014-07-13 12:47:02 -07003138 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3139 : impl(impl),
3140 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003141 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003142 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003143 exitRequested(false),
3144 code(0),
3145 data(NULL),
3146 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003147 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003148
Jesse Hallb154c422014-07-13 12:47:02 -07003149 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003150 status_t waitForResponse() {
3151 do {
3152 looper->pollOnce(-1);
3153 } while (!exitRequested);
3154 return result;
3155 }
3156
Jesse Hallb154c422014-07-13 12:47:02 -07003157 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003158 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003159 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003160 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003161 // Ensure this->result is visible to the binder thread before it
3162 // handles the message.
3163 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003164 looper->sendMessage(this, Message(MSG_EXIT));
3165 }
3166};
3167
3168
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003169status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3170 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003171 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003172 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003173 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003174
3175 if (CC_UNLIKELY(display == 0))
3176 return BAD_VALUE;
3177
3178 if (CC_UNLIKELY(producer == 0))
3179 return BAD_VALUE;
3180
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003181 // if we have secure windows on this display, never allow the screen capture
3182 // unless the producer interface is local (i.e.: we can take a screenshot for
3183 // ourselves).
Marco Nelissen097ca272014-11-14 08:01:01 -08003184 if (!IInterface::asBinder(producer)->localBinder()) {
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003185 Mutex::Autolock _l(mStateLock);
3186 sp<const DisplayDevice> hw(getDisplayDevice(display));
3187 if (hw->getSecureLayerVisible()) {
3188 ALOGW("FB is protected: PERMISSION_DENIED");
3189 return PERMISSION_DENIED;
3190 }
3191 }
3192
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003193 // Convert to surfaceflinger's internal rotation type.
3194 Transform::orientation_flags rotationFlags;
3195 switch (rotation) {
3196 case ISurfaceComposer::eRotateNone:
3197 rotationFlags = Transform::ROT_0;
3198 break;
3199 case ISurfaceComposer::eRotate90:
3200 rotationFlags = Transform::ROT_90;
3201 break;
3202 case ISurfaceComposer::eRotate180:
3203 rotationFlags = Transform::ROT_180;
3204 break;
3205 case ISurfaceComposer::eRotate270:
3206 rotationFlags = Transform::ROT_270;
3207 break;
3208 default:
3209 rotationFlags = Transform::ROT_0;
3210 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3211 break;
3212 }
3213
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003214 class MessageCaptureScreen : public MessageBase {
3215 SurfaceFlinger* flinger;
3216 sp<IBinder> display;
3217 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003218 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003219 uint32_t reqWidth, reqHeight;
3220 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003221 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003222 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003223 status_t result;
3224 public:
3225 MessageCaptureScreen(SurfaceFlinger* flinger,
3226 const sp<IBinder>& display,
3227 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003228 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003229 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003230 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003231 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003232 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003233 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003234 useIdentityTransform(useIdentityTransform),
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003235 rotation(rotation),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003236 result(PERMISSION_DENIED)
3237 {
3238 }
3239 status_t getResult() const {
3240 return result;
3241 }
3242 virtual bool handler() {
3243 Mutex::Autolock _l(flinger->mStateLock);
3244 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003245 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003246 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003247 useIdentityTransform, rotation);
Marco Nelissen097ca272014-11-14 08:01:01 -08003248 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003249 return true;
3250 }
3251 };
3252
Mathias Agopian9eb1f052013-04-10 16:27:17 -07003253 // make sure to process transactions before screenshots -- a transaction
3254 // might already be pending but scheduled for VSYNC; this guarantees we
3255 // will handle it before the screenshot. When VSYNC finally arrives
3256 // the scheduled transaction will be a no-op. If no transactions are
3257 // scheduled at this time, this will end-up being a no-op as well.
3258 mEventQueue.invalidateTransactionNow();
3259
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003260 // this creates a "fake" BBinder which will serve as a "fake" remote
3261 // binder to receive the marshaled calls and forward them to the
3262 // real remote (a BpGraphicBufferProducer)
3263 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3264
3265 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3266 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003267 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003268 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003269 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003270 useIdentityTransform, rotationFlags);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003271
3272 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003273 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003274 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003275 }
3276 return res;
3277}
3278
Mathias Agopian180f10d2013-04-10 22:55:41 -07003279
3280void SurfaceFlinger::renderScreenImplLocked(
3281 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003282 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003283 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003284 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003285{
3286 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003287 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003288
3289 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003290 const int32_t hw_w = hw->getWidth();
3291 const int32_t hw_h = hw->getHeight();
3292 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003293 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003294
Dan Stozac1879002014-05-22 15:59:05 -07003295 // if a default or invalid sourceCrop is passed in, set reasonable values
3296 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3297 !sourceCrop.isValid()) {
3298 sourceCrop.setLeftTop(Point(0, 0));
3299 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3300 }
3301
3302 // ensure that sourceCrop is inside screen
3303 if (sourceCrop.left < 0) {
3304 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3305 }
Dan Stozabe31f442014-06-11 11:20:54 -07003306 if (sourceCrop.right > hw_w) {
3307 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003308 }
3309 if (sourceCrop.top < 0) {
3310 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3311 }
Dan Stozabe31f442014-06-11 11:20:54 -07003312 if (sourceCrop.bottom > hw_h) {
3313 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003314 }
3315
Mathias Agopian180f10d2013-04-10 22:55:41 -07003316 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003317 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003318
3319 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003320 engine.setViewportAndProjection(
3321 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003322 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003323
3324 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003325 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003326
3327 const LayerVector& layers( mDrawingState.layersSortedByZ );
3328 const size_t count = layers.size();
3329 for (size_t i=0 ; i<count ; ++i) {
3330 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003331 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003332 if (state.layerStack == hw->getLayerStack()) {
3333 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3334 if (layer->isVisible()) {
3335 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003336 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003337 if (filtering) layer->setFiltering(false);
3338 }
3339 }
3340 }
3341 }
3342
3343 // compositionComplete is needed for older driver
3344 hw->compositionComplete();
Mathias Agopian931bda12013-08-28 18:11:46 -07003345 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003346}
3347
3348
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003349status_t SurfaceFlinger::captureScreenImplLocked(
3350 const sp<const DisplayDevice>& hw,
3351 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003352 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003353 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003354 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003355{
3356 ATRACE_CALL();
3357
Mathias Agopian180f10d2013-04-10 22:55:41 -07003358 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003359 uint32_t hw_w = hw->getWidth();
3360 uint32_t hw_h = hw->getHeight();
3361
3362 if (rotation & Transform::ROT_90) {
3363 std::swap(hw_w, hw_h);
3364 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003365
Mathias Agopian180f10d2013-04-10 22:55:41 -07003366 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3367 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3368 reqWidth, reqHeight, hw_w, hw_h);
3369 return BAD_VALUE;
3370 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003371
Mathias Agopian180f10d2013-04-10 22:55:41 -07003372 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3373 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3374
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003375 // create a surface (because we're a producer, and we need to
3376 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003377 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003378 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003379
Michael Lentine5a16a622015-05-21 13:48:24 -07003380 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3381 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003382 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3383 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003384
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003385 int err = 0;
3386 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003387 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003388 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3389 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003390
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003391 if (err == NO_ERROR) {
3392 ANativeWindowBuffer* buffer;
3393 /* TODO: Once we have the sync framework everywhere this can use
3394 * server-side waits on the fence that dequeueBuffer returns.
3395 */
3396 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3397 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003398 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003399 // create an EGLImage from the buffer so we can later
3400 // turn it into a texture
3401 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3402 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3403 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003404 // this binds the given EGLImage as a framebuffer for the
3405 // duration of this scope.
3406 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3407 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003408 // this will in fact render into our dequeued buffer
3409 // via an FBO, which means we didn't have to create
3410 // an EGLSurface and therefore we're not
3411 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003412 renderScreenImplLocked(
3413 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3414 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003415
Riley Andrews86639902014-08-15 12:27:24 -07003416 // Attempt to create a sync khr object that can produce a sync point. If that
3417 // isn't available, create a non-dupable sync object in the fallback path and
3418 // wait on it directly.
3419 EGLSyncKHR sync;
3420 if (!DEBUG_SCREENSHOTS) {
3421 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003422 // native fence fd will not be populated until flush() is done.
3423 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003424 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003425 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003426 }
Riley Andrews86639902014-08-15 12:27:24 -07003427 if (sync != EGL_NO_SYNC_KHR) {
3428 // get the sync fd
3429 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3430 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3431 ALOGW("captureScreen: failed to dup sync khr object");
3432 syncFd = -1;
3433 }
3434 eglDestroySyncKHR(mEGLDisplay, sync);
3435 } else {
3436 // fallback path
3437 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3438 if (sync != EGL_NO_SYNC_KHR) {
3439 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3440 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3441 EGLint eglErr = eglGetError();
3442 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3443 ALOGW("captureScreen: fence wait timed out");
3444 } else {
3445 ALOGW_IF(eglErr != EGL_SUCCESS,
3446 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3447 }
3448 eglDestroySyncKHR(mEGLDisplay, sync);
3449 } else {
3450 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3451 }
3452 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003453 if (DEBUG_SCREENSHOTS) {
3454 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3455 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3456 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3457 hw, minLayerZ, maxLayerZ);
3458 delete [] pixels;
3459 }
3460
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003461 } else {
3462 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3463 result = INVALID_OPERATION;
3464 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003465 // destroy our image
3466 eglDestroyImageKHR(mEGLDisplay, image);
3467 } else {
3468 result = BAD_VALUE;
3469 }
Jesse Hallafe2b1f2014-10-21 11:09:17 -07003470 // queueBuffer takes ownership of syncFd
Michael Lentine5a16a622015-05-21 13:48:24 -07003471 result = window->queueBuffer(window, buffer, syncFd);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003472 }
3473 } else {
3474 result = BAD_VALUE;
3475 }
3476 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3477 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003478
Mathias Agopian74c40c02010-09-29 13:02:36 -07003479 return result;
3480}
3481
Mathias Agopiand5556842013-09-19 17:08:37 -07003482void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3483 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003484 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003485 for (size_t y=0 ; y<h ; y++) {
3486 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3487 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003488 if (p[x] != 0xFF000000) return;
3489 }
3490 }
3491 ALOGE("*** we just took a black screenshot ***\n"
3492 "requested minz=%d, maxz=%d, layerStack=%d",
3493 minLayerZ, maxLayerZ, hw->getLayerStack());
3494 const LayerVector& layers( mDrawingState.layersSortedByZ );
3495 const size_t count = layers.size();
3496 for (size_t i=0 ; i<count ; ++i) {
3497 const sp<Layer>& layer(layers[i]);
3498 const Layer::State& state(layer->getDrawingState());
3499 const bool visible = (state.layerStack == hw->getLayerStack())
3500 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3501 && (layer->isVisible());
Greg Hackmann86efcc02014-03-07 12:44:02 -08003502 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003503 visible ? '+' : '-',
3504 i, layer->getName().string(), state.layerStack, state.z,
3505 layer->isVisible(), state.flags, state.alpha);
3506 }
3507 }
3508}
3509
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003510// ---------------------------------------------------------------------------
3511
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003512SurfaceFlinger::LayerVector::LayerVector() {
3513}
3514
3515SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003516 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003517}
3518
3519int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3520 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003521{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003522 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003523 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3524 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003525
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003526 uint32_t ls = l->getCurrentState().layerStack;
3527 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003528 if (ls != rs)
3529 return ls - rs;
3530
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003531 uint32_t lz = l->getCurrentState().z;
3532 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003533 if (lz != rz)
3534 return lz - rz;
3535
3536 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003537}
3538
3539// ---------------------------------------------------------------------------
3540
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003541SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003542 : type(DisplayDevice::DISPLAY_ID_INVALID),
3543 layerStack(DisplayDevice::NO_LAYER_STACK),
3544 orientation(0),
3545 width(0),
3546 height(0),
3547 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003548}
3549
Pablo Ceballos53390e12015-08-04 11:25:59 -07003550SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3551 DisplayDevice::DisplayType type, bool isSecure)
3552 : type(type),
3553 layerStack(DisplayDevice::NO_LAYER_STACK),
3554 orientation(0),
3555 width(0),
3556 height(0),
3557 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003558 viewport.makeInvalid();
3559 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003560}
3561
3562// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003565
3566
3567#if defined(__gl_h_)
3568#error "don't include gl/gl.h in this file"
3569#endif
3570
3571#if defined(__gl2_h_)
3572#error "don't include gl2/gl2.h in this file"
3573#endif