blob: 1976d2e739d37264a34e9a3d7c5e797ce9d35c0b [file] [log] [blame]
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001/*
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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Mark Salyzyn7823e122016-09-29 08:08:05 -070019#include <dlfcn.h>
20#include <errno.h>
21#include <inttypes.h>
22#include <math.h>
23#include <stdatomic.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000024#include <stdint.h>
25#include <sys/types.h>
Dan Stoza9e56aa02015-11-02 13:00:03 -080026
Fabien Sanglard9d96de42016-10-11 00:15:18 +000027#include <mutex>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000028
29#include <EGL/egl.h>
30
Fabien Sanglard9d96de42016-10-11 00:15:18 +000031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000033
34#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
36#include <binder/MemoryHeapBase.h>
37#include <binder/PermissionCache.h>
38
39#include <ui/DisplayInfo.h>
40#include <ui/DisplayStatInfo.h>
41
42#include <gui/BitTube.h>
43#include <gui/BufferQueue.h>
44#include <gui/GuiConfig.h>
45#include <gui/IDisplayEventConnection.h>
46#include <gui/Surface.h>
47#include <gui/GraphicBufferAlloc.h>
48
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/HdrCapabilities.h>
51#include <ui/PixelFormat.h>
52#include <ui/UiConfig.h>
53
54#include <utils/misc.h>
55#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
58#include <utils/Timers.h>
59#include <utils/Trace.h>
60
61#include <private/android_filesystem_config.h>
62#include <private/gui/SyncFeatures.h>
63
64#include <set>
65
66#include "Client.h"
67#include "clz.h"
68#include "Colorizer.h"
69#include "DdmConnection.h"
70#include "DisplayDevice.h"
71#include "DispSync.h"
72#include "EventControlThread.h"
73#include "EventThread.h"
74#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000076#include "LayerDim.h"
77#include "SurfaceFlinger.h"
78
79#include "DisplayHardware/FramebufferSurface.h"
80#include "DisplayHardware/HWComposer.h"
81#include "DisplayHardware/VirtualDisplaySurface.h"
82
83#include "Effects/Daltonizer.h"
84
85#include "RenderEngine/RenderEngine.h"
86#include <cutils/compiler.h>
87
88#define DISPLAY_COUNT 1
89
90/*
91 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
92 * black pixels.
93 */
94#define DEBUG_SCREENSHOTS false
95
96EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
97
Fabien Sanglard9d96de42016-10-11 00:15:18 +000098namespace android {
99
100// This is the phase offset in nanoseconds of the software vsync event
101// relative to the vsync event reported by HWComposer. The software vsync
102// event is when SurfaceFlinger and Choreographer-based applications run each
103// frame.
104//
105// This phase offset allows adjustment of the minimum latency from application
106// wake-up (by Choregographer) time to the time at which the resulting window
107// image is displayed. This value may be either positive (after the HW vsync)
108// or negative (before the HW vsync). Setting it to 0 will result in a
109// minimum latency of two vsync periods because the app and SurfaceFlinger
110// will run just after the HW vsync. Setting it to a positive number will
111// result in the minimum latency being:
112//
113// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
114//
115// Note that reducing this latency makes it more likely for the applications
116// to not have their window content image ready in time. When this happens
117// the latency will end up being an additional vsync period, and animations
118// will hiccup. Therefore, this latency should be tuned somewhat
119// conservatively (or at least with awareness of the trade-off being made).
120static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
121
122// This is the phase offset at which SurfaceFlinger's composition runs.
123static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
124
125// ---------------------------------------------------------------------------
126
127const String16 sHardwareTest("android.permission.HARDWARE_TEST");
128const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
129const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
130const String16 sDump("android.permission.DUMP");
131
132// ---------------------------------------------------------------------------
133
134SurfaceFlinger::SurfaceFlinger()
135 : BnSurfaceComposer(),
136 mTransactionFlags(0),
137 mTransactionPending(false),
138 mAnimTransactionPending(false),
139 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700140 mLayersAdded(false),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000141 mRepaintEverything(0),
142 mRenderEngine(NULL),
143 mBootTime(systemTime()),
144 mVisibleRegionsDirty(false),
145 mHwWorkListDirty(false),
146 mAnimCompositionPending(false),
147 mDebugRegion(0),
148 mDebugDDMS(0),
149 mDebugDisableHWC(0),
150 mDebugDisableTransformHint(0),
151 mDebugInSwapBuffers(0),
152 mLastSwapBufferTime(0),
153 mDebugInTransaction(0),
154 mLastTransactionTime(0),
155 mBootFinished(false),
156 mForceFullDamage(false),
157 mInterceptor(),
158 mPrimaryDispSync("PrimaryDispSync"),
159 mPrimaryHWVsyncEnabled(false),
160 mHWVsyncAvailable(false),
161 mDaltonize(false),
162 mHasColorMatrix(false),
163 mHasPoweredOff(false),
164 mFrameBuckets(),
165 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700166 mLastSwapTime(0),
167 mNumLayers(0)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000168{
169 ALOGI("SurfaceFlinger is starting");
170
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000171 char value[PROPERTY_VALUE_MAX];
172
173 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
174 mGpuToCpuSupported = !atoi(value);
175
176 property_get("debug.sf.showupdates", value, "0");
177 mDebugRegion = atoi(value);
178
179 property_get("debug.sf.ddms", value, "0");
180 mDebugDDMS = atoi(value);
181 if (mDebugDDMS) {
182 if (!startDdmConnection()) {
183 // start failed, and DDMS debugging not enabled
184 mDebugDDMS = 0;
185 }
186 }
187 ALOGI_IF(mDebugRegion, "showupdates enabled");
188 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
189
190 property_get("debug.sf.disable_hwc_vds", value, "0");
191 mUseHwcVirtualDisplays = !atoi(value);
192 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800193
194 property_get("ro.sf.disable_triple_buffer", value, "0");
195 mLayerTripleBufferingDisabled = !atoi(value);
196 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000197}
198
199void SurfaceFlinger::onFirstRef()
200{
201 mEventQueue.init(this);
202}
203
204SurfaceFlinger::~SurfaceFlinger()
205{
206 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
207 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
208 eglTerminate(display);
209}
210
211void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
212{
213 // the window manager died on us. prepare its eulogy.
214
215 // restore initial conditions (default device unblank, etc)
216 initializeDisplays();
217
218 // restart the boot-animation
219 startBootAnim();
220}
221
222sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
223{
224 sp<ISurfaceComposerClient> bclient;
225 sp<Client> client(new Client(this));
226 status_t err = client->initCheck();
227 if (err == NO_ERROR) {
228 bclient = client;
229 }
230 return bclient;
231}
232
233sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
234 bool secure)
235{
236 class DisplayToken : public BBinder {
237 sp<SurfaceFlinger> flinger;
238 virtual ~DisplayToken() {
239 // no more references, this display must be terminated
240 Mutex::Autolock _l(flinger->mStateLock);
241 flinger->mCurrentState.displays.removeItem(this);
242 flinger->setTransactionFlags(eDisplayTransactionNeeded);
243 }
244 public:
245 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
246 : flinger(flinger) {
247 }
248 };
249
250 sp<BBinder> token = new DisplayToken(this);
251
252 Mutex::Autolock _l(mStateLock);
253 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
254 info.displayName = displayName;
255 mCurrentState.displays.add(token, info);
256 mInterceptor.saveDisplayCreation(info);
257 return token;
258}
259
260void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
261 Mutex::Autolock _l(mStateLock);
262
263 ssize_t idx = mCurrentState.displays.indexOfKey(display);
264 if (idx < 0) {
265 ALOGW("destroyDisplay: invalid display token");
266 return;
267 }
268
269 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
270 if (!info.isVirtualDisplay()) {
271 ALOGE("destroyDisplay called for non-virtual display");
272 return;
273 }
274 mInterceptor.saveDisplayDeletion(info.displayId);
275 mCurrentState.displays.removeItemsAt(idx);
276 setTransactionFlags(eDisplayTransactionNeeded);
277}
278
279void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
280 ALOGW_IF(mBuiltinDisplays[type],
281 "Overwriting display token for display type %d", type);
282 mBuiltinDisplays[type] = new BBinder();
283 // All non-virtual displays are currently considered secure.
284 DisplayDeviceState info(type, true);
285 mCurrentState.displays.add(mBuiltinDisplays[type], info);
286 mInterceptor.saveDisplayCreation(info);
287}
288
289sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
290 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
291 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
292 return NULL;
293 }
294 return mBuiltinDisplays[id];
295}
296
297sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
298{
299 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
300 return gba;
301}
302
303void SurfaceFlinger::bootFinished()
304{
305 const nsecs_t now = systemTime();
306 const nsecs_t duration = now - mBootTime;
307 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
308 mBootFinished = true;
309
310 // wait patiently for the window manager death
311 const String16 name("window");
312 sp<IBinder> window(defaultServiceManager()->getService(name));
313 if (window != 0) {
314 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
315 }
316
317 // stop boot animation
318 // formerly we would just kill the process, but we now ask it to exit so it
319 // can choose where to stop the animation.
320 property_set("service.bootanim.exit", "1");
321
322 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
323 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
324 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
325}
326
327void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
328 class MessageDestroyGLTexture : public MessageBase {
329 RenderEngine& engine;
330 uint32_t texture;
331 public:
332 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
333 : engine(engine), texture(texture) {
334 }
335 virtual bool handler() {
336 engine.deleteTextures(1, &texture);
337 return true;
338 }
339 };
340 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
341}
342
343class DispSyncSource : public VSyncSource, private DispSync::Callback {
344public:
345 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
346 const char* name) :
347 mName(name),
348 mValue(0),
349 mTraceVsync(traceVsync),
350 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
351 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
352 mDispSync(dispSync),
353 mCallbackMutex(),
354 mCallback(),
355 mVsyncMutex(),
356 mPhaseOffset(phaseOffset),
357 mEnabled(false) {}
358
359 virtual ~DispSyncSource() {}
360
361 virtual void setVSyncEnabled(bool enable) {
362 Mutex::Autolock lock(mVsyncMutex);
363 if (enable) {
364 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
365 static_cast<DispSync::Callback*>(this));
366 if (err != NO_ERROR) {
367 ALOGE("error registering vsync callback: %s (%d)",
368 strerror(-err), err);
369 }
370 //ATRACE_INT(mVsyncOnLabel.string(), 1);
371 } else {
372 status_t err = mDispSync->removeEventListener(
373 static_cast<DispSync::Callback*>(this));
374 if (err != NO_ERROR) {
375 ALOGE("error unregistering vsync callback: %s (%d)",
376 strerror(-err), err);
377 }
378 //ATRACE_INT(mVsyncOnLabel.string(), 0);
379 }
380 mEnabled = enable;
381 }
382
383 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
384 Mutex::Autolock lock(mCallbackMutex);
385 mCallback = callback;
386 }
387
388 virtual void setPhaseOffset(nsecs_t phaseOffset) {
389 Mutex::Autolock lock(mVsyncMutex);
390
391 // Normalize phaseOffset to [0, period)
392 auto period = mDispSync->getPeriod();
393 phaseOffset %= period;
394 if (phaseOffset < 0) {
395 // If we're here, then phaseOffset is in (-period, 0). After this
396 // operation, it will be in (0, period)
397 phaseOffset += period;
398 }
399 mPhaseOffset = phaseOffset;
400
401 // If we're not enabled, we don't need to mess with the listeners
402 if (!mEnabled) {
403 return;
404 }
405
406 // Remove the listener with the old offset
407 status_t err = mDispSync->removeEventListener(
408 static_cast<DispSync::Callback*>(this));
409 if (err != NO_ERROR) {
410 ALOGE("error unregistering vsync callback: %s (%d)",
411 strerror(-err), err);
412 }
413
414 // Add a listener with the new offset
415 err = mDispSync->addEventListener(mName, mPhaseOffset,
416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
421 }
422
423private:
424 virtual void onDispSyncEvent(nsecs_t when) {
425 sp<VSyncSource::Callback> callback;
426 {
427 Mutex::Autolock lock(mCallbackMutex);
428 callback = mCallback;
429
430 if (mTraceVsync) {
431 mValue = (mValue + 1) % 2;
432 ATRACE_INT(mVsyncEventLabel.string(), mValue);
433 }
434 }
435
436 if (callback != NULL) {
437 callback->onVSyncEvent(when);
438 }
439 }
440
441 const char* const mName;
442
443 int mValue;
444
445 const bool mTraceVsync;
446 const String8 mVsyncOnLabel;
447 const String8 mVsyncEventLabel;
448
449 DispSync* mDispSync;
450
451 Mutex mCallbackMutex; // Protects the following
452 sp<VSyncSource::Callback> mCallback;
453
454 Mutex mVsyncMutex; // Protects the following
455 nsecs_t mPhaseOffset;
456 bool mEnabled;
457};
458
459class InjectVSyncSource : public VSyncSource {
460public:
461 InjectVSyncSource() {}
462
463 virtual ~InjectVSyncSource() {}
464
465 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
466 std::lock_guard<std::mutex> lock(mCallbackMutex);
467 mCallback = callback;
468 }
469
470 virtual void onInjectSyncEvent(nsecs_t when) {
471 std::lock_guard<std::mutex> lock(mCallbackMutex);
472 mCallback->onVSyncEvent(when);
473 }
474
475 virtual void setVSyncEnabled(bool) {}
476 virtual void setPhaseOffset(nsecs_t) {}
477
478private:
479 std::mutex mCallbackMutex; // Protects the following
480 sp<VSyncSource::Callback> mCallback;
481};
482
483void SurfaceFlinger::init() {
484 ALOGI( "SurfaceFlinger's main thread ready to run. "
485 "Initializing graphics H/W...");
486
487 Mutex::Autolock _l(mStateLock);
488
489 // initialize EGL for the default display
490 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
491 eglInitialize(mEGLDisplay, NULL, NULL);
492
493 // start the EventThread
494 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
495 vsyncPhaseOffsetNs, true, "app");
496 mEventThread = new EventThread(vsyncSrc, *this, false);
497 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
498 sfVsyncPhaseOffsetNs, true, "sf");
499 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
500 mEventQueue.setEventThread(mSFEventThread);
501
502 // set SFEventThread to SCHED_FIFO to minimize jitter
503 struct sched_param param = {0};
504 param.sched_priority = 2;
505 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
506 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
507 }
508
509
510 // Initialize the H/W composer object. There may or may not be an
511 // actual hardware composer underneath.
512 mHwc = new HWComposer(this,
513 *static_cast<HWComposer::EventHandler *>(this));
514
515 // get a RenderEngine for the given display / config (can't fail)
516 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
517
518 // retrieve the EGL context that was selected/created
519 mEGLContext = mRenderEngine->getEGLContext();
520
521 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
522 "couldn't create EGLContext");
523
524 // initialize our non-virtual displays
525 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
526 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
527 // set-up the displays that are already connected
528 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
529 // All non-virtual displays are currently considered secure.
530 bool isSecure = true;
531 createBuiltinDisplayLocked(type);
532 wp<IBinder> token = mBuiltinDisplays[i];
533
534 sp<IGraphicBufferProducer> producer;
535 sp<IGraphicBufferConsumer> consumer;
536 BufferQueue::createBufferQueue(&producer, &consumer,
537 new GraphicBufferAlloc());
538
539 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
540 consumer);
541 int32_t hwcId = allocateHwcDisplayId(type);
542 sp<DisplayDevice> hw = new DisplayDevice(this,
543 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
544 fbs, producer,
545 mRenderEngine->getEGLConfig());
546 if (i > DisplayDevice::DISPLAY_PRIMARY) {
547 // FIXME: currently we don't get blank/unblank requests
548 // for displays other than the main display, so we always
549 // assume a connected display is unblanked.
550 ALOGD("marking display %zu as acquired/unblanked", i);
551 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
552 }
553 mDisplays.add(token, hw);
554 }
555 }
556
557 // make the GLContext current so that we can create textures when creating Layers
558 // (which may happens before we render something)
559 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
560
561 mEventControlThread = new EventControlThread(this);
562 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
563
564 // set a fake vsync period if there is no HWComposer
565 if (mHwc->initCheck() != NO_ERROR) {
566 mPrimaryDispSync.setPeriod(16666667);
567 }
568
569 // initialize our drawing state
570 mDrawingState = mCurrentState;
571
572 // set initial conditions (e.g. unblank default device)
573 initializeDisplays();
574
575 mRenderEngine->primeCache();
576
577 // start boot animation
578 startBootAnim();
579}
580
581int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
582 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
583 type : mHwc->allocateDisplayId();
584}
585
586void SurfaceFlinger::startBootAnim() {
587 // start boot animation
588 property_set("service.bootanim.exit", "0");
589 property_set("ctl.start", "bootanim");
590}
591
592size_t SurfaceFlinger::getMaxTextureSize() const {
593 return mRenderEngine->getMaxTextureSize();
594}
595
596size_t SurfaceFlinger::getMaxViewportDims() const {
597 return mRenderEngine->getMaxViewportDims();
598}
599
600// ----------------------------------------------------------------------------
601
602bool SurfaceFlinger::authenticateSurfaceTexture(
603 const sp<IGraphicBufferProducer>& bufferProducer) const {
604 Mutex::Autolock _l(mStateLock);
605 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
606 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
607}
608
Brian Anderson069b3652016-07-22 10:32:47 -0700609status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700610 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700611 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700612 FrameEvent::REQUESTED_PRESENT,
613 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700614 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700615 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700616 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700617 FrameEvent::GL_COMPOSITION_DONE,
618 FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700619 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700620 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700621 };
622 return NO_ERROR;
623}
624
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000625status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
626 Vector<DisplayInfo>* configs) {
627 if ((configs == NULL) || (display.get() == NULL)) {
628 return BAD_VALUE;
629 }
630
631 int32_t type = getDisplayType(display);
632 if (type < 0) return type;
633
634 // TODO: Not sure if display density should handled by SF any longer
635 class Density {
636 static int getDensityFromProperty(char const* propName) {
637 char property[PROPERTY_VALUE_MAX];
638 int density = 0;
639 if (property_get(propName, property, NULL) > 0) {
640 density = atoi(property);
641 }
642 return density;
643 }
644 public:
645 static int getEmuDensity() {
646 return getDensityFromProperty("qemu.sf.lcd_density"); }
647 static int getBuildDensity() {
648 return getDensityFromProperty("ro.sf.lcd_density"); }
649 };
650
651 configs->clear();
652
653 const Vector<HWComposer::DisplayConfig>& hwConfigs =
654 getHwComposer().getConfigs(type);
655 for (size_t c = 0; c < hwConfigs.size(); ++c) {
656 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
657 DisplayInfo info = DisplayInfo();
658
659 float xdpi = hwConfig.xdpi;
660 float ydpi = hwConfig.ydpi;
661
662 if (type == DisplayDevice::DISPLAY_PRIMARY) {
663 // The density of the device is provided by a build property
664 float density = Density::getBuildDensity() / 160.0f;
665 if (density == 0) {
666 // the build doesn't provide a density -- this is wrong!
667 // use xdpi instead
668 ALOGE("ro.sf.lcd_density must be defined as a build property");
669 density = xdpi / 160.0f;
670 }
671 if (Density::getEmuDensity()) {
672 // if "qemu.sf.lcd_density" is specified, it overrides everything
673 xdpi = ydpi = density = Density::getEmuDensity();
674 density /= 160.0f;
675 }
676 info.density = density;
677
678 // TODO: this needs to go away (currently needed only by webkit)
679 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
680 info.orientation = hw->getOrientation();
681 } else {
682 // TODO: where should this value come from?
683 static const int TV_DENSITY = 213;
684 info.density = TV_DENSITY / 160.0f;
685 info.orientation = 0;
686 }
687
688 info.w = hwConfig.width;
689 info.h = hwConfig.height;
690 info.xdpi = xdpi;
691 info.ydpi = ydpi;
692 info.fps = float(1e9 / hwConfig.refresh);
693 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
694
695 // This is how far in advance a buffer must be queued for
696 // presentation at a given time. If you want a buffer to appear
697 // on the screen at time N, you must submit the buffer before
698 // (N - presentationDeadline).
699 //
700 // Normally it's one full refresh period (to give SF a chance to
701 // latch the buffer), but this can be reduced by configuring a
702 // DispSync offset. Any additional delays introduced by the hardware
703 // composer or panel must be accounted for here.
704 //
705 // We add an additional 1ms to allow for processing time and
706 // differences between the ideal and actual refresh rate.
707 info.presentationDeadline =
708 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
709
710 // All non-virtual displays are currently considered secure.
711 info.secure = true;
712
713 configs->push_back(info);
714 }
715
716 return NO_ERROR;
717}
718
719status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
720 DisplayStatInfo* stats) {
721 if (stats == NULL) {
722 return BAD_VALUE;
723 }
724
725 // FIXME for now we always return stats for the primary display
726 memset(stats, 0, sizeof(*stats));
727 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
728 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
729 return NO_ERROR;
730}
731
732int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
733 sp<DisplayDevice> device(getDisplayDevice(display));
734 if (device != NULL) {
735 return device->getActiveConfig();
736 }
737 return BAD_VALUE;
738}
739
740void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
741 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
742 this);
743 int32_t type = hw->getDisplayType();
744 int currentMode = hw->getActiveConfig();
745
746 if (mode == currentMode) {
747 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
748 return;
749 }
750
751 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
752 ALOGW("Trying to set config for virtual display");
753 return;
754 }
755
756 hw->setActiveConfig(mode);
757 getHwComposer().setActiveConfig(type, mode);
758}
759
760status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
761 class MessageSetActiveConfig: public MessageBase {
762 SurfaceFlinger& mFlinger;
763 sp<IBinder> mDisplay;
764 int mMode;
765 public:
766 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
767 int mode) :
768 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
769 virtual bool handler() {
770 Vector<DisplayInfo> configs;
771 mFlinger.getDisplayConfigs(mDisplay, &configs);
772 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
773 ALOGE("Attempt to set active config = %d for display with %zu configs",
774 mMode, configs.size());
775 }
776 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
777 if (hw == NULL) {
778 ALOGE("Attempt to set active config = %d for null display %p",
779 mMode, mDisplay.get());
780 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
781 ALOGW("Attempt to set active config = %d for virtual display",
782 mMode);
783 } else {
784 mFlinger.setActiveConfigInternal(hw, mMode);
785 }
786 return true;
787 }
788 };
789 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
790 postMessageSync(msg);
791 return NO_ERROR;
792}
793
794status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
795 Vector<android_color_mode_t>* outColorModes) {
796 if (outColorModes == nullptr || display.get() == nullptr) {
797 return BAD_VALUE;
798 }
799
800 int32_t type = getDisplayType(display);
801 if (type < 0) return type;
802
803 std::set<android_color_mode_t> colorModes;
804 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
805 colorModes.insert(hwConfig.colorMode);
806 }
807
808 outColorModes->clear();
809 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
810
811 return NO_ERROR;
812}
813
814android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
815 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
816
817 int32_t type = getDisplayType(display);
818 if (type < 0) return static_cast<android_color_mode_t>(type);
819
820 return getHwComposer().getColorMode(type);
821}
822
823status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
824 android_color_mode_t colorMode) {
825 if (display.get() == nullptr || colorMode < 0) {
826 return BAD_VALUE;
827 }
828
829 int32_t type = getDisplayType(display);
830 if (type < 0) return type;
831 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
832 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
833 desiredConfig.colorMode = colorMode;
834 for (size_t c = 0; c < hwConfigs.size(); ++c) {
835 const HWComposer::DisplayConfig config = hwConfigs[c];
836 if (config == desiredConfig) {
837 return setActiveConfig(display, c);
838 }
839 }
840 return BAD_VALUE;
841}
842
843status_t SurfaceFlinger::clearAnimationFrameStats() {
844 Mutex::Autolock _l(mStateLock);
845 mAnimFrameTracker.clearStats();
846 return NO_ERROR;
847}
848
849status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
850 Mutex::Autolock _l(mStateLock);
851 mAnimFrameTracker.getStats(outStats);
852 return NO_ERROR;
853}
854
855status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
856 HdrCapabilities* outCapabilities) const {
857 // HWC1 does not provide HDR capabilities
858 *outCapabilities = HdrCapabilities();
859 return NO_ERROR;
860}
861
862status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
863 if (enable == mInjectVSyncs) {
864 return NO_ERROR;
865 }
866
867 if (enable) {
868 mInjectVSyncs = enable;
869 ALOGV("VSync Injections enabled");
870 if (mVSyncInjector.get() == nullptr) {
871 mVSyncInjector = new InjectVSyncSource();
872 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
873 }
874 mEventQueue.setEventThread(mInjectorEventThread);
875 } else {
876 mInjectVSyncs = enable;
877 ALOGV("VSync Injections disabled");
878 mEventQueue.setEventThread(mSFEventThread);
879 mVSyncInjector.clear();
880 }
881 return NO_ERROR;
882}
883
884status_t SurfaceFlinger::injectVSync(nsecs_t when) {
885 if (!mInjectVSyncs) {
886 ALOGE("VSync Injections not enabled");
887 return BAD_VALUE;
888 }
889 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
890 ALOGV("Injecting VSync inside SurfaceFlinger");
891 mVSyncInjector->onInjectSyncEvent(when);
892 }
893 return NO_ERROR;
894}
895
896// ----------------------------------------------------------------------------
897
898sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
899 return mEventThread->createEventConnection();
900}
901
902// ----------------------------------------------------------------------------
903
904void SurfaceFlinger::waitForEvent() {
905 mEventQueue.waitMessage();
906}
907
908void SurfaceFlinger::signalTransaction() {
909 mEventQueue.invalidate();
910}
911
912void SurfaceFlinger::signalLayerUpdate() {
913 mEventQueue.invalidate();
914}
915
916void SurfaceFlinger::signalRefresh() {
917 mEventQueue.refresh();
918}
919
920status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
921 nsecs_t reltime, uint32_t /* flags */) {
922 return mEventQueue.postMessage(msg, reltime);
923}
924
925status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
926 nsecs_t reltime, uint32_t /* flags */) {
927 status_t res = mEventQueue.postMessage(msg, reltime);
928 if (res == NO_ERROR) {
929 msg->wait();
930 }
931 return res;
932}
933
934void SurfaceFlinger::run() {
935 do {
936 waitForEvent();
937 } while (true);
938}
939
940void SurfaceFlinger::enableHardwareVsync() {
941 Mutex::Autolock _l(mHWVsyncLock);
942 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
943 mPrimaryDispSync.beginResync();
944 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
945 mEventControlThread->setVsyncEnabled(true);
946 mPrimaryHWVsyncEnabled = true;
947 }
948}
949
950void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
951 Mutex::Autolock _l(mHWVsyncLock);
952
953 if (makeAvailable) {
954 mHWVsyncAvailable = true;
955 } else if (!mHWVsyncAvailable) {
956 // Hardware vsync is not currently available, so abort the resync
957 // attempt for now
958 return;
959 }
960
961 const nsecs_t period =
962 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
963
964 mPrimaryDispSync.reset();
965 mPrimaryDispSync.setPeriod(period);
966
967 if (!mPrimaryHWVsyncEnabled) {
968 mPrimaryDispSync.beginResync();
969 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
970 mEventControlThread->setVsyncEnabled(true);
971 mPrimaryHWVsyncEnabled = true;
972 }
973}
974
975void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
976 Mutex::Autolock _l(mHWVsyncLock);
977 if (mPrimaryHWVsyncEnabled) {
978 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
979 mEventControlThread->setVsyncEnabled(false);
980 mPrimaryDispSync.endResync();
981 mPrimaryHWVsyncEnabled = false;
982 }
983 if (makeUnavailable) {
984 mHWVsyncAvailable = false;
985 }
986}
987
988void SurfaceFlinger::resyncWithRateLimit() {
989 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
990 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
991 resyncToHardwareVsync(false);
992 }
993}
994
995void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
996 bool needsHwVsync = false;
997
998 { // Scope for the lock
999 Mutex::Autolock _l(mHWVsyncLock);
1000 if (type == 0 && mPrimaryHWVsyncEnabled) {
1001 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1002 }
1003 }
1004
1005 if (needsHwVsync) {
1006 enableHardwareVsync();
1007 } else {
1008 disableHardwareVsync(false);
1009 }
1010}
1011
1012void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1013 if (mEventThread == NULL) {
1014 // This is a temporary workaround for b/7145521. A non-null pointer
1015 // does not mean EventThread has finished initializing, so this
1016 // is not a correct fix.
1017 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1018 return;
1019 }
1020
1021 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1022 Mutex::Autolock _l(mStateLock);
1023 if (connected) {
1024 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1025 } else {
1026 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1027 mBuiltinDisplays[type].clear();
1028 }
1029 setTransactionFlags(eDisplayTransactionNeeded);
1030
1031 // Defer EventThread notification until SF has updated mDisplays.
1032 }
1033}
1034
1035void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1036 ATRACE_CALL();
1037 getHwComposer().eventControl(disp, event, enabled);
1038}
1039
1040void SurfaceFlinger::onMessageReceived(int32_t what) {
1041 ATRACE_CALL();
1042 switch (what) {
1043 case MessageQueue::INVALIDATE: {
1044 bool refreshNeeded = handleMessageTransaction();
1045 refreshNeeded |= handleMessageInvalidate();
1046 refreshNeeded |= mRepaintEverything;
1047 if (refreshNeeded) {
1048 // Signal a refresh if a transaction modified the window state,
1049 // a new buffer was latched, or if HWC has requested a full
1050 // repaint
1051 signalRefresh();
1052 }
1053 break;
1054 }
1055 case MessageQueue::REFRESH: {
1056 handleMessageRefresh();
1057 break;
1058 }
1059 }
1060}
1061
1062bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001063 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001064 if (transactionFlags) {
1065 handleTransaction(transactionFlags);
1066 return true;
1067 }
1068 return false;
1069}
1070
1071bool SurfaceFlinger::handleMessageInvalidate() {
1072 ATRACE_CALL();
1073 return handlePageFlip();
1074}
1075
1076void SurfaceFlinger::handleMessageRefresh() {
1077 ATRACE_CALL();
1078
1079 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1080
Brian Andersond6927fb2016-07-23 23:37:30 -07001081 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001082 rebuildLayerStacks();
1083 setUpHWComposer();
1084 doDebugFlashRegions();
1085 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001086 postComposition();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001087}
1088
1089void SurfaceFlinger::doDebugFlashRegions()
1090{
1091 // is debugging enabled
1092 if (CC_LIKELY(!mDebugRegion))
1093 return;
1094
1095 const bool repaintEverything = mRepaintEverything;
1096 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1097 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1098 if (hw->isDisplayOn()) {
1099 // transform the dirty region into this screen's coordinate space
1100 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1101 if (!dirtyRegion.isEmpty()) {
1102 // redraw the whole screen
1103 doComposeSurfaces(hw, Region(hw->bounds()));
1104
1105 // and draw the dirty region
1106 const int32_t height = hw->getHeight();
1107 RenderEngine& engine(getRenderEngine());
1108 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1109
1110 hw->compositionComplete();
1111 hw->swapBuffers(getHwComposer());
1112 }
1113 }
1114 }
1115
1116 postFramebuffer();
1117
1118 if (mDebugRegion > 1) {
1119 usleep(mDebugRegion * 1000);
1120 }
1121
1122 HWComposer& hwc(getHwComposer());
1123 if (hwc.initCheck() == NO_ERROR) {
1124 status_t err = hwc.prepare();
1125 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1126 }
1127}
1128
Brian Andersond6927fb2016-07-23 23:37:30 -07001129void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001130{
1131 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001132 mDrawingState.traverseInZOrder([&](Layer* layer) {
1133 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001134 needExtraInvalidate = true;
1135 }
Robert Carr2047fae2016-11-28 14:09:09 -08001136 });
1137
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001138 if (needExtraInvalidate) {
1139 signalLayerUpdate();
1140 }
1141}
1142
Brian Andersond6927fb2016-07-23 23:37:30 -07001143void SurfaceFlinger::postComposition()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001144{
Brian Andersond6927fb2016-07-23 23:37:30 -07001145 const HWComposer& hwc = getHwComposer();
1146 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1147
Brian Anderson3d4039d2016-09-23 16:31:30 -07001148 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1149 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1150 glCompositionDoneFenceTime =
1151 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1152 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1153 } else {
1154 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1155 }
1156 mGlCompositionDoneTimeline.updateSignalTimes();
1157
1158 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1159 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1160 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1161 mDisplayTimeline.push(retireFenceTime);
1162 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001163
Robert Carr2047fae2016-11-28 14:09:09 -08001164 mDrawingState.traverseInZOrder([&](Layer* layer) {
1165 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1166 presentFenceTime, retireFenceTime);
1167
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001168 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001169 recordBufferingStats(layer->getName().string(),
1170 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001171 }
Robert Carr2047fae2016-11-28 14:09:09 -08001172 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001173
Brian Anderson3d4039d2016-09-23 16:31:30 -07001174 if (displayFence->isValid()) {
1175 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001176 enableHardwareVsync();
1177 } else {
1178 disableHardwareVsync(false);
1179 }
1180 }
1181
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001182 if (kIgnorePresentFences) {
1183 if (hw->isDisplayOn()) {
1184 enableHardwareVsync();
1185 }
1186 }
1187
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001188 if (mAnimCompositionPending) {
1189 mAnimCompositionPending = false;
1190
Brian Anderson3d4039d2016-09-23 16:31:30 -07001191 if (retireFenceTime->isValid()) {
1192 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001193 } else {
1194 // The HWC doesn't support present fences, so use the refresh
1195 // timestamp instead.
1196 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1197 mAnimFrameTracker.setActualPresentTime(presentTime);
1198 }
1199 mAnimFrameTracker.advanceFrame();
1200 }
1201
1202 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1203 return;
1204 }
1205
1206 nsecs_t currentTime = systemTime();
1207 if (mHasPoweredOff) {
1208 mHasPoweredOff = false;
1209 } else {
1210 nsecs_t period = mPrimaryDispSync.getPeriod();
1211 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1212 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1213 if (numPeriods < NUM_BUCKETS - 1) {
1214 mFrameBuckets[numPeriods] += elapsedTime;
1215 } else {
1216 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1217 }
1218 mTotalTime += elapsedTime;
1219 }
1220 mLastSwapTime = currentTime;
1221}
1222
1223void SurfaceFlinger::rebuildLayerStacks() {
1224 // rebuild the visible layer list per screen
1225 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1226 ATRACE_CALL();
1227 mVisibleRegionsDirty = false;
1228 invalidateHwcGeometry();
1229
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001230 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1231 Region opaqueRegion;
1232 Region dirtyRegion;
1233 Vector< sp<Layer> > layersSortedByZ;
1234 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1235 const Transform& tr(hw->getTransform());
1236 const Rect bounds(hw->getBounds());
1237 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001238 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1239 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001240
Robert Carr2047fae2016-11-28 14:09:09 -08001241 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001242 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001243 Region drawRegion(tr.transform(
1244 layer->visibleNonTransparentRegion));
1245 drawRegion.andSelf(bounds);
1246 if (!drawRegion.isEmpty()) {
1247 layersSortedByZ.add(layer);
1248 }
1249 }
Robert Carr2047fae2016-11-28 14:09:09 -08001250 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001251 }
1252 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1253 hw->undefinedRegion.set(bounds);
1254 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1255 hw->dirtyRegion.orSelf(dirtyRegion);
1256 }
1257 }
1258}
1259
1260void SurfaceFlinger::setUpHWComposer() {
1261 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1262 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1263 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1264 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1265
1266 // If nothing has changed (!dirty), don't recompose.
1267 // If something changed, but we don't currently have any visible layers,
1268 // and didn't when we last did a composition, then skip it this time.
1269 // The second rule does two things:
1270 // - When all layers are removed from a display, we'll emit one black
1271 // frame, then nothing more until we get new layers.
1272 // - When a display is created with a private layer stack, we won't
1273 // emit any black frames until a layer is added to the layer stack.
1274 bool mustRecompose = dirty && !(empty && wasEmpty);
1275
1276 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1277 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1278 mustRecompose ? "doing" : "skipping",
1279 dirty ? "+" : "-",
1280 empty ? "+" : "-",
1281 wasEmpty ? "+" : "-");
1282
1283 mDisplays[dpy]->beginFrame(mustRecompose);
1284
1285 if (mustRecompose) {
1286 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1287 }
1288 }
1289
1290 HWComposer& hwc(getHwComposer());
1291 if (hwc.initCheck() == NO_ERROR) {
1292 // build the h/w work list
1293 if (CC_UNLIKELY(mHwWorkListDirty)) {
1294 mHwWorkListDirty = false;
1295 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1296 sp<const DisplayDevice> hw(mDisplays[dpy]);
1297 const int32_t id = hw->getHwcDisplayId();
1298 if (id >= 0) {
1299 const Vector< sp<Layer> >& currentLayers(
1300 hw->getVisibleLayersSortedByZ());
1301 const size_t count = currentLayers.size();
1302 if (hwc.createWorkList(id, count) == NO_ERROR) {
1303 HWComposer::LayerListIterator cur = hwc.begin(id);
1304 const HWComposer::LayerListIterator end = hwc.end(id);
1305 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1306 const sp<Layer>& layer(currentLayers[i]);
1307 layer->setGeometry(hw, *cur);
1308 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1309 cur->setSkip(true);
1310 }
1311 }
1312 }
1313 }
1314 }
1315 }
1316
1317 // set the per-frame data
1318 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1319 sp<const DisplayDevice> hw(mDisplays[dpy]);
1320 const int32_t id = hw->getHwcDisplayId();
1321 if (id >= 0) {
1322 const Vector< sp<Layer> >& currentLayers(
1323 hw->getVisibleLayersSortedByZ());
1324 const size_t count = currentLayers.size();
1325 HWComposer::LayerListIterator cur = hwc.begin(id);
1326 const HWComposer::LayerListIterator end = hwc.end(id);
1327 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1328 /*
1329 * update the per-frame h/w composer data for each layer
1330 * and build the transparent region of the FB
1331 */
1332 const sp<Layer>& layer(currentLayers[i]);
1333 layer->setPerFrameData(hw, *cur);
1334 }
1335 }
1336 }
1337
1338 // If possible, attempt to use the cursor overlay on each display.
1339 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1340 sp<const DisplayDevice> hw(mDisplays[dpy]);
1341 const int32_t id = hw->getHwcDisplayId();
1342 if (id >= 0) {
1343 const Vector< sp<Layer> >& currentLayers(
1344 hw->getVisibleLayersSortedByZ());
1345 const size_t count = currentLayers.size();
1346 HWComposer::LayerListIterator cur = hwc.begin(id);
1347 const HWComposer::LayerListIterator end = hwc.end(id);
1348 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1349 const sp<Layer>& layer(currentLayers[i]);
1350 if (layer->isPotentialCursor()) {
1351 cur->setIsCursorLayerHint();
1352 break;
1353 }
1354 }
1355 }
1356 }
1357
1358 status_t err = hwc.prepare();
1359 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1360
1361 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1362 sp<const DisplayDevice> hw(mDisplays[dpy]);
1363 hw->prepareFrame(hwc);
1364 }
1365 }
1366}
1367
1368void SurfaceFlinger::doComposition() {
1369 ATRACE_CALL();
1370 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1371 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1372 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1373 if (hw->isDisplayOn()) {
1374 // transform the dirty region into this screen's coordinate space
1375 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1376
1377 // repaint the framebuffer (if needed)
1378 doDisplayComposition(hw, dirtyRegion);
1379
1380 hw->dirtyRegion.clear();
1381 hw->flip(hw->swapRegion);
1382 hw->swapRegion.clear();
1383 }
1384 // inform the h/w that we're done compositing
1385 hw->compositionComplete();
1386 }
1387 postFramebuffer();
1388}
1389
1390void SurfaceFlinger::postFramebuffer()
1391{
1392 ATRACE_CALL();
1393
1394 const nsecs_t now = systemTime();
1395 mDebugInSwapBuffers = now;
1396
1397 HWComposer& hwc(getHwComposer());
1398 if (hwc.initCheck() == NO_ERROR) {
1399 if (!hwc.supportsFramebufferTarget()) {
1400 // EGL spec says:
1401 // "surface must be bound to the calling thread's current context,
1402 // for the current rendering API."
1403 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1404 }
1405 hwc.commit();
1406 }
1407
1408 // make the default display current because the VirtualDisplayDevice code cannot
1409 // deal with dequeueBuffer() being called outside of the composition loop; however
1410 // the code below can call glFlush() which is allowed (and does in some case) call
1411 // dequeueBuffer().
1412 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1413
1414 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1415 sp<const DisplayDevice> hw(mDisplays[dpy]);
1416 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1417 hw->onSwapBuffersCompleted(hwc);
1418 const size_t count = currentLayers.size();
1419 int32_t id = hw->getHwcDisplayId();
1420 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1421 HWComposer::LayerListIterator cur = hwc.begin(id);
1422 const HWComposer::LayerListIterator end = hwc.end(id);
1423 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1424 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1425 }
1426 } else {
1427 for (size_t i = 0; i < count; i++) {
1428 currentLayers[i]->onLayerDisplayed(hw, NULL);
1429 }
1430 }
1431 }
1432
1433 mLastSwapBufferTime = systemTime() - now;
1434 mDebugInSwapBuffers = 0;
1435
1436 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1437 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1438 logFrameStats();
1439 }
1440}
1441
1442void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1443{
1444 ATRACE_CALL();
1445
1446 // here we keep a copy of the drawing state (that is the state that's
1447 // going to be overwritten by handleTransactionLocked()) outside of
1448 // mStateLock so that the side-effects of the State assignment
1449 // don't happen with mStateLock held (which can cause deadlocks).
1450 State drawingState(mDrawingState);
1451
1452 Mutex::Autolock _l(mStateLock);
1453 const nsecs_t now = systemTime();
1454 mDebugInTransaction = now;
1455
1456 // Here we're guaranteed that some transaction flags are set
1457 // so we can call handleTransactionLocked() unconditionally.
1458 // We call getTransactionFlags(), which will also clear the flags,
1459 // with mStateLock held to guarantee that mCurrentState won't change
1460 // until the transaction is committed.
1461
1462 transactionFlags = getTransactionFlags(eTransactionMask);
1463 handleTransactionLocked(transactionFlags);
1464
1465 mLastTransactionTime = systemTime() - now;
1466 mDebugInTransaction = 0;
1467 invalidateHwcGeometry();
1468 // here the transaction has been committed
1469}
1470
1471void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1472{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001473 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001474 mCurrentState.traverseInZOrder([](Layer* layer) {
1475 layer->notifyAvailableFrames();
1476 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001477
1478 /*
1479 * Traversal of the children
1480 * (perform the transaction for each of them if needed)
1481 */
1482
1483 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001484 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001485 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001486 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001487
1488 const uint32_t flags = layer->doTransaction(0);
1489 if (flags & Layer::eVisibleRegion)
1490 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001491 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001492 }
1493
1494 /*
1495 * Perform display own transactions if needed
1496 */
1497
1498 if (transactionFlags & eDisplayTransactionNeeded) {
1499 // here we take advantage of Vector's copy-on-write semantics to
1500 // improve performance by skipping the transaction entirely when
1501 // know that the lists are identical
1502 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1503 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1504 if (!curr.isIdenticalTo(draw)) {
1505 mVisibleRegionsDirty = true;
1506 const size_t cc = curr.size();
1507 size_t dc = draw.size();
1508
1509 // find the displays that were removed
1510 // (ie: in drawing state but not in current state)
1511 // also handle displays that changed
1512 // (ie: displays that are in both lists)
1513 for (size_t i=0 ; i<dc ; i++) {
1514 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1515 if (j < 0) {
1516 // in drawing state but not in current state
1517 if (!draw[i].isMainDisplay()) {
1518 // Call makeCurrent() on the primary display so we can
1519 // be sure that nothing associated with this display
1520 // is current.
1521 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1522 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1523 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1524 if (hw != NULL)
1525 hw->disconnect(getHwComposer());
1526 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1527 mEventThread->onHotplugReceived(draw[i].type, false);
1528 mDisplays.removeItem(draw.keyAt(i));
1529 } else {
1530 ALOGW("trying to remove the main display");
1531 }
1532 } else {
1533 // this display is in both lists. see if something changed.
1534 const DisplayDeviceState& state(curr[j]);
1535 const wp<IBinder>& display(curr.keyAt(j));
1536 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1537 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1538 if (state_binder != draw_binder) {
1539 // changing the surface is like destroying and
1540 // recreating the DisplayDevice, so we just remove it
1541 // from the drawing state, so that it get re-added
1542 // below.
1543 sp<DisplayDevice> hw(getDisplayDevice(display));
1544 if (hw != NULL)
1545 hw->disconnect(getHwComposer());
1546 mDisplays.removeItem(display);
1547 mDrawingState.displays.removeItemsAt(i);
1548 dc--; i--;
1549 // at this point we must loop to the next item
1550 continue;
1551 }
1552
1553 const sp<DisplayDevice> disp(getDisplayDevice(display));
1554 if (disp != NULL) {
1555 if (state.layerStack != draw[i].layerStack) {
1556 disp->setLayerStack(state.layerStack);
1557 }
1558 if ((state.orientation != draw[i].orientation)
1559 || (state.viewport != draw[i].viewport)
1560 || (state.frame != draw[i].frame))
1561 {
1562 disp->setProjection(state.orientation,
1563 state.viewport, state.frame);
1564 }
1565 if (state.width != draw[i].width || state.height != draw[i].height) {
1566 disp->setDisplaySize(state.width, state.height);
1567 }
1568 }
1569 }
1570 }
1571
1572 // find displays that were added
1573 // (ie: in current state but not in drawing state)
1574 for (size_t i=0 ; i<cc ; i++) {
1575 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1576 const DisplayDeviceState& state(curr[i]);
1577
1578 sp<DisplaySurface> dispSurface;
1579 sp<IGraphicBufferProducer> producer;
1580 sp<IGraphicBufferProducer> bqProducer;
1581 sp<IGraphicBufferConsumer> bqConsumer;
1582 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1583 new GraphicBufferAlloc());
1584
1585 int32_t hwcDisplayId = -1;
1586 if (state.isVirtualDisplay()) {
1587 // Virtual displays without a surface are dormant:
1588 // they have external state (layer stack, projection,
1589 // etc.) but no internal state (i.e. a DisplayDevice).
1590 if (state.surface != NULL) {
1591
1592 int width = 0;
1593 int status = state.surface->query(
1594 NATIVE_WINDOW_WIDTH, &width);
1595 ALOGE_IF(status != NO_ERROR,
1596 "Unable to query width (%d)", status);
1597 int height = 0;
1598 status = state.surface->query(
1599 NATIVE_WINDOW_HEIGHT, &height);
1600 ALOGE_IF(status != NO_ERROR,
1601 "Unable to query height (%d)", status);
1602 if (mUseHwcVirtualDisplays &&
1603 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1604 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1605 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1606 hwcDisplayId = allocateHwcDisplayId(state.type);
1607 }
1608
1609 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1610 *mHwc, hwcDisplayId, state.surface,
1611 bqProducer, bqConsumer, state.displayName);
1612
1613 dispSurface = vds;
1614 producer = vds;
1615 }
1616 } else {
1617 ALOGE_IF(state.surface!=NULL,
1618 "adding a supported display, but rendering "
1619 "surface is provided (%p), ignoring it",
1620 state.surface.get());
1621 hwcDisplayId = allocateHwcDisplayId(state.type);
1622 // for supported (by hwc) displays we provide our
1623 // own rendering surface
1624 dispSurface = new FramebufferSurface(*mHwc, state.type,
1625 bqConsumer);
1626 producer = bqProducer;
1627 }
1628
1629 const wp<IBinder>& display(curr.keyAt(i));
1630 if (dispSurface != NULL) {
1631 sp<DisplayDevice> hw = new DisplayDevice(this,
1632 state.type, hwcDisplayId,
1633 mHwc->getFormat(hwcDisplayId), state.isSecure,
1634 display, dispSurface, producer,
1635 mRenderEngine->getEGLConfig());
1636 hw->setLayerStack(state.layerStack);
1637 hw->setProjection(state.orientation,
1638 state.viewport, state.frame);
1639 hw->setDisplayName(state.displayName);
1640 mDisplays.add(display, hw);
1641 if (state.isVirtualDisplay()) {
1642 if (hwcDisplayId >= 0) {
1643 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1644 hw->getWidth(), hw->getHeight(),
1645 hw->getFormat());
1646 }
1647 } else {
1648 mEventThread->onHotplugReceived(state.type, true);
1649 }
1650 }
1651 }
1652 }
1653 }
1654 }
1655
1656 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1657 // The transform hint might have changed for some layers
1658 // (either because a display has changed, or because a layer
1659 // as changed).
1660 //
1661 // Walk through all the layers in currentLayers,
1662 // and update their transform hint.
1663 //
1664 // If a layer is visible only on a single display, then that
1665 // display is used to calculate the hint, otherwise we use the
1666 // default display.
1667 //
1668 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1669 // the hint is set before we acquire a buffer from the surface texture.
1670 //
1671 // NOTE: layer transactions have taken place already, so we use their
1672 // drawing state. However, SurfaceFlinger's own transaction has not
1673 // happened yet, so we must use the current state layer list
1674 // (soon to become the drawing state list).
1675 //
1676 sp<const DisplayDevice> disp;
1677 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001678 bool first = true;
1679 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001680 // NOTE: we rely on the fact that layers are sorted by
1681 // layerStack first (so we don't have to traverse the list
1682 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001684 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001685 currentlayerStack = layerStack;
1686 // figure out if this layerstack is mirrored
1687 // (more than one display) if so, pick the default display,
1688 // if not, pick the only display it's on.
1689 disp.clear();
1690 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1691 sp<const DisplayDevice> hw(mDisplays[dpy]);
1692 if (hw->getLayerStack() == currentlayerStack) {
1693 if (disp == NULL) {
1694 disp = hw;
1695 } else {
1696 disp = NULL;
1697 break;
1698 }
1699 }
1700 }
1701 }
1702 if (disp == NULL) {
1703 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1704 // redraw after transform hint changes. See bug 8508397.
1705
1706 // could be null when this layer is using a layerStack
1707 // that is not visible on any display. Also can occur at
1708 // screen off/on times.
1709 disp = getDefaultDisplayDevice();
1710 }
1711 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001712
1713 first = false;
1714 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001715 }
1716
1717
1718 /*
1719 * Perform our own transaction if needed
1720 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001721
1722 if (mLayersAdded) {
1723 mLayersAdded = false;
1724 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001725 mVisibleRegionsDirty = true;
1726 }
1727
1728 // some layers might have been removed, so
1729 // we need to update the regions they're exposing.
1730 if (mLayersRemoved) {
1731 mLayersRemoved = false;
1732 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001733 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001734 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001735 // this layer is not visible anymore
1736 // TODO: we could traverse the tree from front to back and
1737 // compute the actual visible region
1738 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001739 Region visibleReg;
1740 visibleReg.set(layer->computeScreenBounds());
1741 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001742 }
Robert Carr2047fae2016-11-28 14:09:09 -08001743 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001744 }
1745
1746 commitTransaction();
1747
1748 updateCursorAsync();
1749}
1750
1751void SurfaceFlinger::updateCursorAsync()
1752{
1753 HWComposer& hwc(getHwComposer());
1754 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1755 sp<const DisplayDevice> hw(mDisplays[dpy]);
1756 const int32_t id = hw->getHwcDisplayId();
1757 if (id < 0) {
1758 continue;
1759 }
1760 const Vector< sp<Layer> >& currentLayers(
1761 hw->getVisibleLayersSortedByZ());
1762 const size_t count = currentLayers.size();
1763 HWComposer::LayerListIterator cur = hwc.begin(id);
1764 const HWComposer::LayerListIterator end = hwc.end(id);
1765 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1766 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1767 continue;
1768 }
1769 const sp<Layer>& layer(currentLayers[i]);
1770 Rect cursorPos = layer->getPosition(hw);
1771 hwc.setCursorPositionAsync(id, cursorPos);
1772 break;
1773 }
1774 }
1775}
1776
1777void SurfaceFlinger::commitTransaction()
1778{
1779 if (!mLayersPendingRemoval.isEmpty()) {
1780 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001781 for (const auto& l : mLayersPendingRemoval) {
1782 recordBufferingStats(l->getName().string(),
1783 l->getOccupancyHistory(true));
1784 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001785 }
1786 mLayersPendingRemoval.clear();
1787 }
1788
1789 // If this transaction is part of a window animation then the next frame
1790 // we composite should be considered an animation as well.
1791 mAnimCompositionPending = mAnimTransactionPending;
1792
1793 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001794 mDrawingState.traverseInZOrder([](Layer* layer) {
1795 layer->commitChildList();
1796 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001797 mTransactionPending = false;
1798 mAnimTransactionPending = false;
1799 mTransactionCV.broadcast();
1800}
1801
Robert Carr2047fae2016-11-28 14:09:09 -08001802void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001803 Region& outDirtyRegion, Region& outOpaqueRegion)
1804{
1805 ATRACE_CALL();
1806
1807 Region aboveOpaqueLayers;
1808 Region aboveCoveredLayers;
1809 Region dirty;
1810
1811 outDirtyRegion.clear();
1812
Robert Carr2047fae2016-11-28 14:09:09 -08001813 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001814 // start with the whole surface at its current location
1815 const Layer::State& s(layer->getDrawingState());
1816
1817 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001818 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001819 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001820
1821 /*
1822 * opaqueRegion: area of a surface that is fully opaque.
1823 */
1824 Region opaqueRegion;
1825
1826 /*
1827 * visibleRegion: area of a surface that is visible on screen
1828 * and not fully transparent. This is essentially the layer's
1829 * footprint minus the opaque regions above it.
1830 * Areas covered by a translucent surface are considered visible.
1831 */
1832 Region visibleRegion;
1833
1834 /*
1835 * coveredRegion: area of a surface that is covered by all
1836 * visible regions above it (which includes the translucent areas).
1837 */
1838 Region coveredRegion;
1839
1840 /*
1841 * transparentRegion: area of a surface that is hinted to be completely
1842 * transparent. This is only used to tell when the layer has no visible
1843 * non-transparent regions and can be removed from the layer list. It
1844 * does not affect the visibleRegion of this layer or any layers
1845 * beneath it. The hint may not be correct if apps don't respect the
1846 * SurfaceView restrictions (which, sadly, some don't).
1847 */
1848 Region transparentRegion;
1849
1850
1851 // handle hidden surfaces by setting the visible region to empty
1852 if (CC_LIKELY(layer->isVisible())) {
1853 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001854 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001855 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001856 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001857 if (!visibleRegion.isEmpty()) {
1858 // Remove the transparent area from the visible region
1859 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001860 if (tr.preserveRects()) {
1861 // transform the transparent region
1862 transparentRegion = tr.transform(s.activeTransparentRegion);
1863 } else {
1864 // transformation too complex, can't do the
1865 // transparent region optimization.
1866 transparentRegion.clear();
1867 }
1868 }
1869
1870 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001871 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001872 if (s.alpha==255 && !translucent &&
1873 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1874 // the opaque region is the layer's footprint
1875 opaqueRegion = visibleRegion;
1876 }
1877 }
1878 }
1879
1880 // Clip the covered region to the visible region
1881 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1882
1883 // Update aboveCoveredLayers for next (lower) layer
1884 aboveCoveredLayers.orSelf(visibleRegion);
1885
1886 // subtract the opaque region covered by the layers above us
1887 visibleRegion.subtractSelf(aboveOpaqueLayers);
1888
1889 // compute this layer's dirty region
1890 if (layer->contentDirty) {
1891 // we need to invalidate the whole region
1892 dirty = visibleRegion;
1893 // as well, as the old visible region
1894 dirty.orSelf(layer->visibleRegion);
1895 layer->contentDirty = false;
1896 } else {
1897 /* compute the exposed region:
1898 * the exposed region consists of two components:
1899 * 1) what's VISIBLE now and was COVERED before
1900 * 2) what's EXPOSED now less what was EXPOSED before
1901 *
1902 * note that (1) is conservative, we start with the whole
1903 * visible region but only keep what used to be covered by
1904 * something -- which mean it may have been exposed.
1905 *
1906 * (2) handles areas that were not covered by anything but got
1907 * exposed because of a resize.
1908 */
1909 const Region newExposed = visibleRegion - coveredRegion;
1910 const Region oldVisibleRegion = layer->visibleRegion;
1911 const Region oldCoveredRegion = layer->coveredRegion;
1912 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1913 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1914 }
1915 dirty.subtractSelf(aboveOpaqueLayers);
1916
1917 // accumulate to the screen dirty region
1918 outDirtyRegion.orSelf(dirty);
1919
1920 // Update aboveOpaqueLayers for next (lower) layer
1921 aboveOpaqueLayers.orSelf(opaqueRegion);
1922
1923 // Store the visible region in screen space
1924 layer->setVisibleRegion(visibleRegion);
1925 layer->setCoveredRegion(coveredRegion);
1926 layer->setVisibleNonTransparentRegion(
1927 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08001928 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001929
1930 outOpaqueRegion = aboveOpaqueLayers;
1931}
1932
1933void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1934 const Region& dirty) {
1935 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1936 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1937 if (hw->getLayerStack() == layerStack) {
1938 hw->dirtyRegion.orSelf(dirty);
1939 }
1940 }
1941}
1942
1943bool SurfaceFlinger::handlePageFlip()
1944{
Brian Andersond6927fb2016-07-23 23:37:30 -07001945 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001946 Region dirtyRegion;
1947
1948 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001949 bool frameQueued = false;
1950
1951 // Store the set of layers that need updates. This set must not change as
1952 // buffers are being latched, as this could result in a deadlock.
1953 // Example: Two producers share the same command stream and:
1954 // 1.) Layer 0 is latched
1955 // 2.) Layer 0 gets a new frame
1956 // 2.) Layer 1 gets a new frame
1957 // 3.) Layer 1 is latched.
1958 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1959 // second frame. But layer 0's second frame could be waiting on display.
1960 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08001961 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001962 if (layer->hasQueuedFrame()) {
1963 frameQueued = true;
1964 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08001965 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001966 } else {
1967 layer->useEmptyDamage();
1968 }
1969 } else {
1970 layer->useEmptyDamage();
1971 }
Robert Carr2047fae2016-11-28 14:09:09 -08001972 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001973 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1974 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07001975 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001976 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001977 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001978 }
1979
1980 mVisibleRegionsDirty |= visibleRegions;
1981
1982 // If we will need to wake up at some time in the future to deal with a
1983 // queued frame that shouldn't be displayed during this vsync period, wake
1984 // up during the next vsync period to check again.
1985 if (frameQueued && layersWithQueuedFrames.empty()) {
1986 signalLayerUpdate();
1987 }
1988
1989 // Only continue with the refresh if there is actually new work to do
1990 return !layersWithQueuedFrames.empty();
1991}
1992
1993void SurfaceFlinger::invalidateHwcGeometry()
1994{
1995 mHwWorkListDirty = true;
1996}
1997
1998
1999void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2000 const Region& inDirtyRegion)
2001{
2002 // We only need to actually compose the display if:
2003 // 1) It is being handled by hardware composer, which may need this to
2004 // keep its virtual display state machine in sync, or
2005 // 2) There is work to be done (the dirty region isn't empty)
2006 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2007 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2008 return;
2009 }
2010
2011 Region dirtyRegion(inDirtyRegion);
2012
2013 // compute the invalid region
2014 hw->swapRegion.orSelf(dirtyRegion);
2015
2016 uint32_t flags = hw->getFlags();
2017 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2018 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2019 // takes a rectangle, we must make sure to update that whole
2020 // rectangle in that case
2021 dirtyRegion.set(hw->swapRegion.bounds());
2022 } else {
2023 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2024 // We need to redraw the rectangle that will be updated
2025 // (pushed to the framebuffer).
2026 // This is needed because PARTIAL_UPDATES only takes one
2027 // rectangle instead of a region (see DisplayDevice::flip())
2028 dirtyRegion.set(hw->swapRegion.bounds());
2029 } else {
2030 // we need to redraw everything (the whole screen)
2031 dirtyRegion.set(hw->bounds());
2032 hw->swapRegion = dirtyRegion;
2033 }
2034 }
2035
2036 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2037 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2038 } else {
2039 RenderEngine& engine(getRenderEngine());
2040 mat4 colorMatrix = mColorMatrix;
2041 if (mDaltonize) {
2042 colorMatrix = colorMatrix * mDaltonizer();
2043 }
2044 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2045 doComposeSurfaces(hw, dirtyRegion);
2046 engine.setupColorTransform(oldMatrix);
2047 }
2048
2049 // update the swap region and clear the dirty region
2050 hw->swapRegion.orSelf(dirtyRegion);
2051
2052 // swap buffers (presentation)
2053 hw->swapBuffers(getHwComposer());
2054}
2055
2056bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2057{
2058 RenderEngine& engine(getRenderEngine());
2059 const int32_t id = hw->getHwcDisplayId();
2060 HWComposer& hwc(getHwComposer());
2061 HWComposer::LayerListIterator cur = hwc.begin(id);
2062 const HWComposer::LayerListIterator end = hwc.end(id);
2063
2064 bool hasGlesComposition = hwc.hasGlesComposition(id);
2065 if (hasGlesComposition) {
2066 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2067 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2068 hw->getDisplayName().string());
2069 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2070 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2071 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2072 }
2073 return false;
2074 }
2075
2076 // Never touch the framebuffer if we don't have any framebuffer layers
2077 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2078 if (hasHwcComposition) {
2079 // when using overlays, we assume a fully transparent framebuffer
2080 // NOTE: we could reduce how much we need to clear, for instance
2081 // remove where there are opaque FB layers. however, on some
2082 // GPUs doing a "clean slate" clear might be more efficient.
2083 // We'll revisit later if needed.
2084 engine.clearWithColor(0, 0, 0, 0);
2085 } else {
2086 // we start with the whole screen area
2087 const Region bounds(hw->getBounds());
2088
2089 // we remove the scissor part
2090 // we're left with the letterbox region
2091 // (common case is that letterbox ends-up being empty)
2092 const Region letterbox(bounds.subtract(hw->getScissor()));
2093
2094 // compute the area to clear
2095 Region region(hw->undefinedRegion.merge(letterbox));
2096
2097 // but limit it to the dirty region
2098 region.andSelf(dirty);
2099
2100 // screen is already cleared here
2101 if (!region.isEmpty()) {
2102 // can happen with SurfaceView
2103 drawWormhole(hw, region);
2104 }
2105 }
2106
2107 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2108 // just to be on the safe side, we don't set the
2109 // scissor on the main display. It should never be needed
2110 // anyways (though in theory it could since the API allows it).
2111 const Rect& bounds(hw->getBounds());
2112 const Rect& scissor(hw->getScissor());
2113 if (scissor != bounds) {
2114 // scissor doesn't match the screen's dimensions, so we
2115 // need to clear everything outside of it and enable
2116 // the GL scissor so we don't draw anything where we shouldn't
2117
2118 // enable scissor for this frame
2119 const uint32_t height = hw->getHeight();
2120 engine.setScissor(scissor.left, height - scissor.bottom,
2121 scissor.getWidth(), scissor.getHeight());
2122 }
2123 }
2124 }
2125
2126 /*
2127 * and then, render the layers targeted at the framebuffer
2128 */
2129
2130 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2131 const size_t count = layers.size();
2132 const Transform& tr = hw->getTransform();
2133 if (cur != end) {
2134 // we're using h/w composer
2135 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2136 const sp<Layer>& layer(layers[i]);
2137 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2138 if (!clip.isEmpty()) {
2139 switch (cur->getCompositionType()) {
2140 case HWC_CURSOR_OVERLAY:
2141 case HWC_OVERLAY: {
2142 const Layer::State& state(layer->getDrawingState());
2143 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2144 && i
2145 && layer->isOpaque(state) && (state.alpha == 0xFF)
2146 && hasGlesComposition) {
2147 // never clear the very first layer since we're
2148 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002149 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002150 }
2151 break;
2152 }
2153 case HWC_FRAMEBUFFER: {
2154 layer->draw(hw, clip);
2155 break;
2156 }
2157 case HWC_FRAMEBUFFER_TARGET: {
2158 // this should not happen as the iterator shouldn't
2159 // let us get there.
2160 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2161 break;
2162 }
2163 }
2164 }
2165 layer->setAcquireFence(hw, *cur);
2166 }
2167 } else {
2168 // we're not using h/w composer
2169 for (size_t i=0 ; i<count ; ++i) {
2170 const sp<Layer>& layer(layers[i]);
2171 const Region clip(dirty.intersect(
2172 tr.transform(layer->visibleRegion)));
2173 if (!clip.isEmpty()) {
2174 layer->draw(hw, clip);
2175 }
2176 }
2177 }
2178
2179 // disable scissor at the end of the frame
2180 engine.disableScissor();
2181 return true;
2182}
2183
2184void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2185 const int32_t height = hw->getHeight();
2186 RenderEngine& engine(getRenderEngine());
2187 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2188}
2189
2190status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2191 const sp<IBinder>& handle,
2192 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002193 const sp<Layer>& lbc,
2194 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002195{
2196 // add this layer to the current state list
2197 {
2198 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002199 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002200 return NO_MEMORY;
2201 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002202 if (parent == nullptr) {
2203 mCurrentState.layersSortedByZ.add(lbc);
2204 } else {
2205 parent->addChild(lbc);
2206 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002207 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002208 mLayersAdded = true;
2209 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002210 }
2211
2212 // attach this layer to the client
2213 client->attachLayer(handle, lbc);
2214
2215 return NO_ERROR;
2216}
2217
2218status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2219 Mutex::Autolock _l(mStateLock);
2220 sp<Layer> layer = weakLayer.promote();
2221 if (layer == nullptr) {
2222 // The layer has already been removed, carry on
2223 return NO_ERROR;
2224 }
2225
Robert Carr1f0a16a2016-10-24 16:27:39 -07002226 const auto& p = layer->getParent();
2227 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2228 mCurrentState.layersSortedByZ.remove(layer);
2229
2230 if (index < 0) {
2231 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2232 layer->getName().string(),
2233 (p != nullptr) ? p->getName().string() : "no-parent");
2234 return BAD_VALUE;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002235 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002236
2237 mLayersPendingRemoval.add(layer);
2238 mLayersRemoved = true;
2239 mNumLayers--;
2240 setTransactionFlags(eTransactionNeeded);
2241 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002242}
2243
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002244uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002245 return android_atomic_release_load(&mTransactionFlags);
2246}
2247
2248uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2249 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2250}
2251
2252uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2253 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2254 if ((old & flags)==0) { // wake the server up
2255 signalTransaction();
2256 }
2257 return old;
2258}
2259
2260void SurfaceFlinger::setTransactionState(
2261 const Vector<ComposerState>& state,
2262 const Vector<DisplayState>& displays,
2263 uint32_t flags)
2264{
2265 ATRACE_CALL();
2266 Mutex::Autolock _l(mStateLock);
2267 uint32_t transactionFlags = 0;
2268
2269 if (flags & eAnimation) {
2270 // For window updates that are part of an animation we must wait for
2271 // previous animation "frames" to be handled.
2272 while (mAnimTransactionPending) {
2273 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2274 if (CC_UNLIKELY(err != NO_ERROR)) {
2275 // just in case something goes wrong in SF, return to the
2276 // caller after a few seconds.
2277 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2278 "waiting for previous animation frame");
2279 mAnimTransactionPending = false;
2280 break;
2281 }
2282 }
2283 }
2284
2285 size_t count = displays.size();
2286 for (size_t i=0 ; i<count ; i++) {
2287 const DisplayState& s(displays[i]);
2288 transactionFlags |= setDisplayStateLocked(s);
2289 }
2290
2291 count = state.size();
2292 for (size_t i=0 ; i<count ; i++) {
2293 const ComposerState& s(state[i]);
2294 // Here we need to check that the interface we're given is indeed
2295 // one of our own. A malicious client could give us a NULL
2296 // IInterface, or one of its own or even one of our own but a
2297 // different type. All these situations would cause us to crash.
2298 //
2299 // NOTE: it would be better to use RTTI as we could directly check
2300 // that we have a Client*. however, RTTI is disabled in Android.
2301 if (s.client != NULL) {
2302 sp<IBinder> binder = IInterface::asBinder(s.client);
2303 if (binder != NULL) {
2304 String16 desc(binder->getInterfaceDescriptor());
2305 if (desc == ISurfaceComposerClient::descriptor) {
2306 sp<Client> client( static_cast<Client *>(s.client.get()) );
2307 transactionFlags |= setClientStateLocked(client, s.state);
2308 }
2309 }
2310 }
2311 }
2312
2313 // If a synchronous transaction is explicitly requested without any changes,
2314 // force a transaction anyway. This can be used as a flush mechanism for
2315 // previous async transactions.
2316 if (transactionFlags == 0 && (flags & eSynchronous)) {
2317 transactionFlags = eTransactionNeeded;
2318 }
2319
2320 if (transactionFlags) {
2321 if (mInterceptor.isEnabled()) {
2322 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2323 }
2324
2325 // this triggers the transaction
2326 setTransactionFlags(transactionFlags);
2327
2328 // if this is a synchronous transaction, wait for it to take effect
2329 // before returning.
2330 if (flags & eSynchronous) {
2331 mTransactionPending = true;
2332 }
2333 if (flags & eAnimation) {
2334 mAnimTransactionPending = true;
2335 }
2336 while (mTransactionPending) {
2337 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2338 if (CC_UNLIKELY(err != NO_ERROR)) {
2339 // just in case something goes wrong in SF, return to the
2340 // called after a few seconds.
2341 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2342 mTransactionPending = false;
2343 break;
2344 }
2345 }
2346 }
2347}
2348
2349uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2350{
2351 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2352 if (dpyIdx < 0)
2353 return 0;
2354
2355 uint32_t flags = 0;
2356 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2357 if (disp.isValid()) {
2358 const uint32_t what = s.what;
2359 if (what & DisplayState::eSurfaceChanged) {
2360 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2361 disp.surface = s.surface;
2362 flags |= eDisplayTransactionNeeded;
2363 }
2364 }
2365 if (what & DisplayState::eLayerStackChanged) {
2366 if (disp.layerStack != s.layerStack) {
2367 disp.layerStack = s.layerStack;
2368 flags |= eDisplayTransactionNeeded;
2369 }
2370 }
2371 if (what & DisplayState::eDisplayProjectionChanged) {
2372 if (disp.orientation != s.orientation) {
2373 disp.orientation = s.orientation;
2374 flags |= eDisplayTransactionNeeded;
2375 }
2376 if (disp.frame != s.frame) {
2377 disp.frame = s.frame;
2378 flags |= eDisplayTransactionNeeded;
2379 }
2380 if (disp.viewport != s.viewport) {
2381 disp.viewport = s.viewport;
2382 flags |= eDisplayTransactionNeeded;
2383 }
2384 }
2385 if (what & DisplayState::eDisplaySizeChanged) {
2386 if (disp.width != s.width) {
2387 disp.width = s.width;
2388 flags |= eDisplayTransactionNeeded;
2389 }
2390 if (disp.height != s.height) {
2391 disp.height = s.height;
2392 flags |= eDisplayTransactionNeeded;
2393 }
2394 }
2395 }
2396 return flags;
2397}
2398
2399uint32_t SurfaceFlinger::setClientStateLocked(
2400 const sp<Client>& client,
2401 const layer_state_t& s)
2402{
2403 uint32_t flags = 0;
2404 sp<Layer> layer(client->getLayerUser(s.surface));
2405 if (layer != 0) {
2406 const uint32_t what = s.what;
2407 bool geometryAppliesWithResize =
2408 what & layer_state_t::eGeometryAppliesWithResize;
2409 if (what & layer_state_t::ePositionChanged) {
2410 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2411 flags |= eTraversalNeeded;
2412 }
2413 }
2414 if (what & layer_state_t::eLayerChanged) {
2415 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002416 const auto& p = layer->getParent();
2417 if (p == nullptr) {
2418 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2419 if (layer->setLayer(s.z) && idx >= 0) {
2420 mCurrentState.layersSortedByZ.removeAt(idx);
2421 mCurrentState.layersSortedByZ.add(layer);
2422 // we need traversal (state changed)
2423 // AND transaction (list changed)
2424 flags |= eTransactionNeeded|eTraversalNeeded;
2425 }
2426 } else {
2427 if (p->setChildLayer(layer, s.z)) {
2428 flags |= eTransactionNeeded|eTraversalNeeded;
2429 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002430 }
2431 }
2432 if (what & layer_state_t::eSizeChanged) {
2433 if (layer->setSize(s.w, s.h)) {
2434 flags |= eTraversalNeeded;
2435 }
2436 }
2437 if (what & layer_state_t::eAlphaChanged) {
2438 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2439 flags |= eTraversalNeeded;
2440 }
2441 if (what & layer_state_t::eMatrixChanged) {
2442 if (layer->setMatrix(s.matrix))
2443 flags |= eTraversalNeeded;
2444 }
2445 if (what & layer_state_t::eTransparentRegionChanged) {
2446 if (layer->setTransparentRegionHint(s.transparentRegion))
2447 flags |= eTraversalNeeded;
2448 }
2449 if (what & layer_state_t::eFlagsChanged) {
2450 if (layer->setFlags(s.flags, s.mask))
2451 flags |= eTraversalNeeded;
2452 }
2453 if (what & layer_state_t::eCropChanged) {
2454 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2455 flags |= eTraversalNeeded;
2456 }
2457 if (what & layer_state_t::eFinalCropChanged) {
2458 if (layer->setFinalCrop(s.finalCrop))
2459 flags |= eTraversalNeeded;
2460 }
2461 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002462 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002463 // We only allow setting layer stacks for top level layers,
2464 // everything else inherits layer stack from its parent.
2465 if (layer->hasParent()) {
2466 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2467 layer->getName().string());
2468 } else if (idx < 0) {
2469 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2470 "that also does not appear in the top level layer list. Something"
2471 " has gone wrong.", layer->getName().string());
2472 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002473 mCurrentState.layersSortedByZ.removeAt(idx);
2474 mCurrentState.layersSortedByZ.add(layer);
2475 // we need traversal (state changed)
2476 // AND transaction (list changed)
2477 flags |= eTransactionNeeded|eTraversalNeeded;
2478 }
2479 }
2480 if (what & layer_state_t::eDeferTransaction) {
2481 layer->deferTransactionUntil(s.handle, s.frameNumber);
2482 // We don't trigger a traversal here because if no other state is
2483 // changed, we don't want this to cause any more work
2484 }
2485 if (what & layer_state_t::eOverrideScalingModeChanged) {
2486 layer->setOverrideScalingMode(s.overrideScalingMode);
2487 // We don't trigger a traversal here because if no other state is
2488 // changed, we don't want this to cause any more work
2489 }
2490 }
2491 return flags;
2492}
2493
2494status_t SurfaceFlinger::createLayer(
2495 const String8& name,
2496 const sp<Client>& client,
2497 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002498 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
2499 sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002500{
2501 if (int32_t(w|h) < 0) {
2502 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2503 int(w), int(h));
2504 return BAD_VALUE;
2505 }
2506
2507 status_t result = NO_ERROR;
2508
2509 sp<Layer> layer;
2510
2511 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2512 case ISurfaceComposerClient::eFXSurfaceNormal:
2513 result = createNormalLayer(client,
2514 name, w, h, flags, format,
2515 handle, gbp, &layer);
2516 break;
2517 case ISurfaceComposerClient::eFXSurfaceDim:
2518 result = createDimLayer(client,
2519 name, w, h, flags,
2520 handle, gbp, &layer);
2521 break;
2522 default:
2523 result = BAD_VALUE;
2524 break;
2525 }
2526
2527 if (result != NO_ERROR) {
2528 return result;
2529 }
2530
Robert Carr1f0a16a2016-10-24 16:27:39 -07002531 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002532 if (result != NO_ERROR) {
2533 return result;
2534 }
2535 mInterceptor.saveSurfaceCreation(layer);
2536
2537 setTransactionFlags(eTransactionNeeded);
2538 return result;
2539}
2540
2541status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2542 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2543 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2544{
2545 // initialize the surfaces
2546 switch (format) {
2547 case PIXEL_FORMAT_TRANSPARENT:
2548 case PIXEL_FORMAT_TRANSLUCENT:
2549 format = PIXEL_FORMAT_RGBA_8888;
2550 break;
2551 case PIXEL_FORMAT_OPAQUE:
2552 format = PIXEL_FORMAT_RGBX_8888;
2553 break;
2554 }
2555
2556 *outLayer = new Layer(this, client, name, w, h, flags);
2557 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2558 if (err == NO_ERROR) {
2559 *handle = (*outLayer)->getHandle();
2560 *gbp = (*outLayer)->getProducer();
2561 }
2562
2563 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2564 return err;
2565}
2566
2567status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2568 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2569 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2570{
2571 *outLayer = new LayerDim(this, client, name, w, h, flags);
2572 *handle = (*outLayer)->getHandle();
2573 *gbp = (*outLayer)->getProducer();
2574 return NO_ERROR;
2575}
2576
2577status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2578{
2579 // called by the window manager when it wants to remove a Layer
2580 status_t err = NO_ERROR;
2581 sp<Layer> l(client->getLayerUser(handle));
2582 if (l != NULL) {
2583 mInterceptor.saveSurfaceDeletion(l);
2584 err = removeLayer(l);
2585 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2586 "error removing layer=%p (%s)", l.get(), strerror(-err));
2587 }
2588 return err;
2589}
2590
2591status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2592{
2593 // called by ~LayerCleaner() when all references to the IBinder (handle)
2594 // are gone
2595 return removeLayer(layer);
2596}
2597
2598// ---------------------------------------------------------------------------
2599
2600void SurfaceFlinger::onInitializeDisplays() {
2601 // reset screen orientation and use primary layer stack
2602 Vector<ComposerState> state;
2603 Vector<DisplayState> displays;
2604 DisplayState d;
2605 d.what = DisplayState::eDisplayProjectionChanged |
2606 DisplayState::eLayerStackChanged;
2607 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2608 d.layerStack = 0;
2609 d.orientation = DisplayState::eOrientationDefault;
2610 d.frame.makeInvalid();
2611 d.viewport.makeInvalid();
2612 d.width = 0;
2613 d.height = 0;
2614 displays.add(d);
2615 setTransactionState(state, displays, 0);
2616 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2617
2618 const nsecs_t period =
2619 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2620 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2621}
2622
2623void SurfaceFlinger::initializeDisplays() {
2624 class MessageScreenInitialized : public MessageBase {
2625 SurfaceFlinger* flinger;
2626 public:
2627 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2628 virtual bool handler() {
2629 flinger->onInitializeDisplays();
2630 return true;
2631 }
2632 };
2633 sp<MessageBase> msg = new MessageScreenInitialized(this);
2634 postMessageAsync(msg); // we may be called from main thread, use async message
2635}
2636
2637void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2638 int mode) {
2639 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2640 this);
2641 int32_t type = hw->getDisplayType();
2642 int currentMode = hw->getPowerMode();
2643
2644 if (mode == currentMode) {
2645 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2646 return;
2647 }
2648
2649 hw->setPowerMode(mode);
2650 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2651 ALOGW("Trying to set power mode for virtual display");
2652 return;
2653 }
2654
2655 if (mInterceptor.isEnabled()) {
2656 Mutex::Autolock _l(mStateLock);
2657 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2658 if (idx < 0) {
2659 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2660 return;
2661 }
2662 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2663 }
2664
2665 if (currentMode == HWC_POWER_MODE_OFF) {
2666 // Turn on the display
2667 getHwComposer().setPowerMode(type, mode);
2668 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2669 // FIXME: eventthread only knows about the main display right now
2670 mEventThread->onScreenAcquired();
2671 resyncToHardwareVsync(true);
2672 }
2673
2674 mVisibleRegionsDirty = true;
2675 mHasPoweredOff = true;
2676 repaintEverything();
2677
2678 struct sched_param param = {0};
2679 param.sched_priority = 1;
2680 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2681 ALOGW("Couldn't set SCHED_FIFO on display on");
2682 }
2683 } else if (mode == HWC_POWER_MODE_OFF) {
2684 // Turn off the display
2685 struct sched_param param = {0};
2686 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2687 ALOGW("Couldn't set SCHED_OTHER on display off");
2688 }
2689
2690 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2691 disableHardwareVsync(true); // also cancels any in-progress resync
2692
2693 // FIXME: eventthread only knows about the main display right now
2694 mEventThread->onScreenReleased();
2695 }
2696
2697 getHwComposer().setPowerMode(type, mode);
2698 mVisibleRegionsDirty = true;
2699 // from this point on, SF will stop drawing on this display
2700 } else {
2701 getHwComposer().setPowerMode(type, mode);
2702 }
2703}
2704
2705void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2706 class MessageSetPowerMode: public MessageBase {
2707 SurfaceFlinger& mFlinger;
2708 sp<IBinder> mDisplay;
2709 int mMode;
2710 public:
2711 MessageSetPowerMode(SurfaceFlinger& flinger,
2712 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2713 mDisplay(disp) { mMode = mode; }
2714 virtual bool handler() {
2715 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2716 if (hw == NULL) {
2717 ALOGE("Attempt to set power mode = %d for null display %p",
2718 mMode, mDisplay.get());
2719 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2720 ALOGW("Attempt to set power mode = %d for virtual display",
2721 mMode);
2722 } else {
2723 mFlinger.setPowerModeInternal(hw, mMode);
2724 }
2725 return true;
2726 }
2727 };
2728 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2729 postMessageSync(msg);
2730}
2731
2732// ---------------------------------------------------------------------------
2733
2734status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2735{
2736 String8 result;
2737
2738 IPCThreadState* ipc = IPCThreadState::self();
2739 const int pid = ipc->getCallingPid();
2740 const int uid = ipc->getCallingUid();
2741 if ((uid != AID_SHELL) &&
2742 !PermissionCache::checkPermission(sDump, pid, uid)) {
2743 result.appendFormat("Permission Denial: "
2744 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2745 } else {
2746 // Try to get the main lock, but give up after one second
2747 // (this would indicate SF is stuck, but we want to be able to
2748 // print something in dumpsys).
2749 status_t err = mStateLock.timedLock(s2ns(1));
2750 bool locked = (err == NO_ERROR);
2751 if (!locked) {
2752 result.appendFormat(
2753 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2754 "dumping anyways (no locks held)\n", strerror(-err), err);
2755 }
2756
2757 bool dumpAll = true;
2758 size_t index = 0;
2759 size_t numArgs = args.size();
2760 if (numArgs) {
2761 if ((index < numArgs) &&
2762 (args[index] == String16("--list"))) {
2763 index++;
2764 listLayersLocked(args, index, result);
2765 dumpAll = false;
2766 }
2767
2768 if ((index < numArgs) &&
2769 (args[index] == String16("--latency"))) {
2770 index++;
2771 dumpStatsLocked(args, index, result);
2772 dumpAll = false;
2773 }
2774
2775 if ((index < numArgs) &&
2776 (args[index] == String16("--latency-clear"))) {
2777 index++;
2778 clearStatsLocked(args, index, result);
2779 dumpAll = false;
2780 }
2781
2782 if ((index < numArgs) &&
2783 (args[index] == String16("--dispsync"))) {
2784 index++;
2785 mPrimaryDispSync.dump(result);
2786 dumpAll = false;
2787 }
2788
2789 if ((index < numArgs) &&
2790 (args[index] == String16("--static-screen"))) {
2791 index++;
2792 dumpStaticScreenStats(result);
2793 dumpAll = false;
2794 }
2795
2796 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002797 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002798 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002799 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002800 dumpAll = false;
2801 }
2802 }
2803
2804 if (dumpAll) {
2805 dumpAllLocked(args, index, result);
2806 }
2807
2808 if (locked) {
2809 mStateLock.unlock();
2810 }
2811 }
2812 write(fd, result.string(), result.size());
2813 return NO_ERROR;
2814}
2815
2816void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2817 size_t& /* index */, String8& result) const
2818{
Robert Carr2047fae2016-11-28 14:09:09 -08002819 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002820 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002822}
2823
2824void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2825 String8& result) const
2826{
2827 String8 name;
2828 if (index < args.size()) {
2829 name = String8(args[index]);
2830 index++;
2831 }
2832
2833 const nsecs_t period =
2834 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2835 result.appendFormat("%" PRId64 "\n", period);
2836
2837 if (name.isEmpty()) {
2838 mAnimFrameTracker.dumpStats(result);
2839 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002840 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002841 if (name == layer->getName()) {
2842 layer->dumpFrameStats(result);
2843 }
Robert Carr2047fae2016-11-28 14:09:09 -08002844 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002845 }
2846}
2847
2848void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2849 String8& /* result */)
2850{
2851 String8 name;
2852 if (index < args.size()) {
2853 name = String8(args[index]);
2854 index++;
2855 }
2856
Robert Carr2047fae2016-11-28 14:09:09 -08002857 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002858 if (name.isEmpty() || (name == layer->getName())) {
2859 layer->clearFrameStats();
2860 }
Robert Carr2047fae2016-11-28 14:09:09 -08002861 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002862
2863 mAnimFrameTracker.clearStats();
2864}
2865
2866// This should only be called from the main thread. Otherwise it would need
2867// the lock and should use mCurrentState rather than mDrawingState.
2868void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002869 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002870 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002872
2873 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2874}
2875
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002876void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002877{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002878 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002879#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002880 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002881#endif
2882#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002883 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002884#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002885 if (isLayerTripleBufferingDisabled())
2886 result.append(" DISABLE_TRIPLE_BUFFERING");
2887 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002888}
2889
2890void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2891{
2892 result.appendFormat("Static screen stats:\n");
2893 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2894 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2895 float percent = 100.0f *
2896 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2897 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2898 b + 1, bucketTimeSec, percent);
2899 }
2900 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2901 float percent = 100.0f *
2902 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2903 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2904 NUM_BUCKETS - 1, bucketTimeSec, percent);
2905}
2906
Brian Andersond6927fb2016-07-23 23:37:30 -07002907void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
2908 result.appendFormat("Layer frame timestamps:\n");
2909
2910 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2911 const size_t count = currentLayers.size();
2912 for (size_t i=0 ; i<count ; i++) {
2913 currentLayers[i]->dumpFrameEvents(result);
2914 }
2915}
2916
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002917void SurfaceFlinger::recordBufferingStats(const char* layerName,
2918 std::vector<OccupancyTracker::Segment>&& history) {
2919 Mutex::Autolock lock(mBufferingStatsMutex);
2920 auto& stats = mBufferingStats[layerName];
2921 for (const auto& segment : history) {
2922 if (!segment.usedThirdBuffer) {
2923 stats.twoBufferTime += segment.totalTime;
2924 }
2925 if (segment.occupancyAverage < 1.0f) {
2926 stats.doubleBufferedTime += segment.totalTime;
2927 } else if (segment.occupancyAverage < 2.0f) {
2928 stats.tripleBufferedTime += segment.totalTime;
2929 }
2930 ++stats.numSegments;
2931 stats.totalTime += segment.totalTime;
2932 }
2933}
2934
2935void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2936 result.append("Buffering stats:\n");
2937 result.append(" [Layer name] <Active time> <Two buffer> "
2938 "<Double buffered> <Triple buffered>\n");
2939 Mutex::Autolock lock(mBufferingStatsMutex);
2940 typedef std::tuple<std::string, float, float, float> BufferTuple;
2941 std::map<float, BufferTuple, std::greater<float>> sorted;
2942 for (const auto& statsPair : mBufferingStats) {
2943 const char* name = statsPair.first.c_str();
2944 const BufferingStats& stats = statsPair.second;
2945 if (stats.numSegments == 0) {
2946 continue;
2947 }
2948 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2949 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2950 stats.totalTime;
2951 float doubleBufferRatio = static_cast<float>(
2952 stats.doubleBufferedTime) / stats.totalTime;
2953 float tripleBufferRatio = static_cast<float>(
2954 stats.tripleBufferedTime) / stats.totalTime;
2955 sorted.insert({activeTime, {name, twoBufferRatio,
2956 doubleBufferRatio, tripleBufferRatio}});
2957 }
2958 for (const auto& sortedPair : sorted) {
2959 float activeTime = sortedPair.first;
2960 const BufferTuple& values = sortedPair.second;
2961 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2962 std::get<0>(values).c_str(), activeTime,
2963 std::get<1>(values), std::get<2>(values),
2964 std::get<3>(values));
2965 }
2966 result.append("\n");
2967}
2968
2969void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2970 String8& result) const
2971{
2972 bool colorize = false;
2973 if (index < args.size()
2974 && (args[index] == String16("--color"))) {
2975 colorize = true;
2976 index++;
2977 }
2978
2979 Colorizer colorizer(colorize);
2980
2981 // figure out if we're stuck somewhere
2982 const nsecs_t now = systemTime();
2983 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2984 const nsecs_t inTransaction(mDebugInTransaction);
2985 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2986 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2987
2988 /*
2989 * Dump library configuration.
2990 */
2991
2992 colorizer.bold(result);
2993 result.append("Build configuration:");
2994 colorizer.reset(result);
2995 appendSfConfigString(result);
2996 appendUiConfigString(result);
2997 appendGuiConfigString(result);
2998 result.append("\n");
2999
3000 colorizer.bold(result);
3001 result.append("Sync configuration: ");
3002 colorizer.reset(result);
3003 result.append(SyncFeatures::getInstance().toString());
3004 result.append("\n");
3005
3006 colorizer.bold(result);
3007 result.append("DispSync configuration: ");
3008 colorizer.reset(result);
3009 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3010 "present offset %d ns (refresh %" PRId64 " ns)",
3011 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3012 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3013 result.append("\n");
3014
3015 // Dump static screen stats
3016 result.append("\n");
3017 dumpStaticScreenStats(result);
3018 result.append("\n");
3019
3020 dumpBufferingStats(result);
3021
3022 /*
3023 * Dump the visible layer list
3024 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003025 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003026 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003027 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003028 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003029 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003030 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003031
3032 /*
3033 * Dump Display state
3034 */
3035
3036 colorizer.bold(result);
3037 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3038 colorizer.reset(result);
3039 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3040 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3041 hw->dump(result);
3042 }
3043
3044 /*
3045 * Dump SurfaceFlinger global state
3046 */
3047
3048 colorizer.bold(result);
3049 result.append("SurfaceFlinger global state:\n");
3050 colorizer.reset(result);
3051
3052 HWComposer& hwc(getHwComposer());
3053 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3054
3055 colorizer.bold(result);
3056 result.appendFormat("EGL implementation : %s\n",
3057 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3058 colorizer.reset(result);
3059 result.appendFormat("%s\n",
3060 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3061
3062 mRenderEngine->dump(result);
3063
3064 hw->undefinedRegion.dump(result, "undefinedRegion");
3065 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3066 hw->getOrientation(), hw->isDisplayOn());
3067 result.appendFormat(
3068 " last eglSwapBuffers() time: %f us\n"
3069 " last transaction time : %f us\n"
3070 " transaction-flags : %08x\n"
3071 " refresh-rate : %f fps\n"
3072 " x-dpi : %f\n"
3073 " y-dpi : %f\n"
3074 " gpu_to_cpu_unsupported : %d\n"
3075 ,
3076 mLastSwapBufferTime/1000.0,
3077 mLastTransactionTime/1000.0,
3078 mTransactionFlags,
3079 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3080 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3081 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3082 !mGpuToCpuSupported);
3083
3084 result.appendFormat(" eglSwapBuffers time: %f us\n",
3085 inSwapBuffersDuration/1000.0);
3086
3087 result.appendFormat(" transaction time: %f us\n",
3088 inTransactionDuration/1000.0);
3089
3090 /*
3091 * VSYNC state
3092 */
3093 mEventThread->dump(result);
3094
3095 /*
3096 * Dump HWComposer state
3097 */
3098 colorizer.bold(result);
3099 result.append("h/w composer state:\n");
3100 colorizer.reset(result);
3101 result.appendFormat(" h/w composer %s and %s\n",
3102 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3103 (mDebugDisableHWC || mDebugRegion || mDaltonize
3104 || mHasColorMatrix) ? "disabled" : "enabled");
3105 hwc.dump(result);
3106
3107 /*
3108 * Dump gralloc state
3109 */
3110 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3111 alloc.dump(result);
3112}
3113
3114const Vector< sp<Layer> >&
3115SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3116 // Note: mStateLock is held here
3117 wp<IBinder> dpy;
3118 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3119 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3120 dpy = mDisplays.keyAt(i);
3121 break;
3122 }
3123 }
3124 if (dpy == NULL) {
3125 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3126 // Just use the primary display so we have something to return
3127 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3128 }
3129 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3130}
3131
3132bool SurfaceFlinger::startDdmConnection()
3133{
3134 void* libddmconnection_dso =
3135 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3136 if (!libddmconnection_dso) {
3137 return false;
3138 }
3139 void (*DdmConnection_start)(const char* name);
3140 DdmConnection_start =
3141 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3142 if (!DdmConnection_start) {
3143 dlclose(libddmconnection_dso);
3144 return false;
3145 }
3146 (*DdmConnection_start)(getServiceName());
3147 return true;
3148}
3149
3150status_t SurfaceFlinger::onTransact(
3151 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3152{
3153 switch (code) {
3154 case CREATE_CONNECTION:
3155 case CREATE_DISPLAY:
3156 case SET_TRANSACTION_STATE:
3157 case BOOT_FINISHED:
3158 case CLEAR_ANIMATION_FRAME_STATS:
3159 case GET_ANIMATION_FRAME_STATS:
3160 case SET_POWER_MODE:
3161 case GET_HDR_CAPABILITIES:
3162 {
3163 // codes that require permission check
3164 IPCThreadState* ipc = IPCThreadState::self();
3165 const int pid = ipc->getCallingPid();
3166 const int uid = ipc->getCallingUid();
3167 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3168 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3169 ALOGE("Permission Denial: "
3170 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3171 return PERMISSION_DENIED;
3172 }
3173 break;
3174 }
3175 case CAPTURE_SCREEN:
3176 {
3177 // codes that require permission check
3178 IPCThreadState* ipc = IPCThreadState::self();
3179 const int pid = ipc->getCallingPid();
3180 const int uid = ipc->getCallingUid();
3181 if ((uid != AID_GRAPHICS) &&
3182 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3183 ALOGE("Permission Denial: "
3184 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3185 return PERMISSION_DENIED;
3186 }
3187 break;
3188 }
3189 }
3190
3191 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3192 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3193 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3194 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3195 IPCThreadState* ipc = IPCThreadState::self();
3196 const int pid = ipc->getCallingPid();
3197 const int uid = ipc->getCallingUid();
3198 ALOGE("Permission Denial: "
3199 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3200 return PERMISSION_DENIED;
3201 }
3202 int n;
3203 switch (code) {
3204 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3205 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3206 return NO_ERROR;
3207 case 1002: // SHOW_UPDATES
3208 n = data.readInt32();
3209 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3210 invalidateHwcGeometry();
3211 repaintEverything();
3212 return NO_ERROR;
3213 case 1004:{ // repaint everything
3214 repaintEverything();
3215 return NO_ERROR;
3216 }
3217 case 1005:{ // force transaction
3218 setTransactionFlags(
3219 eTransactionNeeded|
3220 eDisplayTransactionNeeded|
3221 eTraversalNeeded);
3222 return NO_ERROR;
3223 }
3224 case 1006:{ // send empty update
3225 signalRefresh();
3226 return NO_ERROR;
3227 }
3228 case 1008: // toggle use of hw composer
3229 n = data.readInt32();
3230 mDebugDisableHWC = n ? 1 : 0;
3231 invalidateHwcGeometry();
3232 repaintEverything();
3233 return NO_ERROR;
3234 case 1009: // toggle use of transform hint
3235 n = data.readInt32();
3236 mDebugDisableTransformHint = n ? 1 : 0;
3237 invalidateHwcGeometry();
3238 repaintEverything();
3239 return NO_ERROR;
3240 case 1010: // interrogate.
3241 reply->writeInt32(0);
3242 reply->writeInt32(0);
3243 reply->writeInt32(mDebugRegion);
3244 reply->writeInt32(0);
3245 reply->writeInt32(mDebugDisableHWC);
3246 return NO_ERROR;
3247 case 1013: {
3248 Mutex::Autolock _l(mStateLock);
3249 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3250 reply->writeInt32(hw->getPageFlipCount());
3251 return NO_ERROR;
3252 }
3253 case 1014: {
3254 // daltonize
3255 n = data.readInt32();
3256 switch (n % 10) {
3257 case 1:
3258 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3259 break;
3260 case 2:
3261 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3262 break;
3263 case 3:
3264 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3265 break;
3266 }
3267 if (n >= 10) {
3268 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3269 } else {
3270 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3271 }
3272 mDaltonize = n > 0;
3273 invalidateHwcGeometry();
3274 repaintEverything();
3275 return NO_ERROR;
3276 }
3277 case 1015: {
3278 // apply a color matrix
3279 n = data.readInt32();
3280 mHasColorMatrix = n ? 1 : 0;
3281 if (n) {
3282 // color matrix is sent as mat3 matrix followed by vec3
3283 // offset, then packed into a mat4 where the last row is
3284 // the offset and extra values are 0
3285 for (size_t i = 0 ; i < 4; i++) {
3286 for (size_t j = 0; j < 4; j++) {
3287 mColorMatrix[i][j] = data.readFloat();
3288 }
3289 }
3290 } else {
3291 mColorMatrix = mat4();
3292 }
3293 invalidateHwcGeometry();
3294 repaintEverything();
3295 return NO_ERROR;
3296 }
3297 // This is an experimental interface
3298 // Needs to be shifted to proper binder interface when we productize
3299 case 1016: {
3300 n = data.readInt32();
3301 mPrimaryDispSync.setRefreshSkipCount(n);
3302 return NO_ERROR;
3303 }
3304 case 1017: {
3305 n = data.readInt32();
3306 mForceFullDamage = static_cast<bool>(n);
3307 return NO_ERROR;
3308 }
3309 case 1018: { // Modify Choreographer's phase offset
3310 n = data.readInt32();
3311 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3312 return NO_ERROR;
3313 }
3314 case 1019: { // Modify SurfaceFlinger's phase offset
3315 n = data.readInt32();
3316 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3317 return NO_ERROR;
3318 }
3319 case 1020: { // Layer updates interceptor
3320 n = data.readInt32();
3321 if (n) {
3322 ALOGV("Interceptor enabled");
3323 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3324 }
3325 else{
3326 ALOGV("Interceptor disabled");
3327 mInterceptor.disable();
3328 }
3329 return NO_ERROR;
3330 }
3331 case 1021: { // Disable HWC virtual displays
3332 n = data.readInt32();
3333 mUseHwcVirtualDisplays = !n;
3334 return NO_ERROR;
3335 }
3336 }
3337 }
3338 return err;
3339}
3340
3341void SurfaceFlinger::repaintEverything() {
3342 android_atomic_or(1, &mRepaintEverything);
3343 signalTransaction();
3344}
3345
3346// ---------------------------------------------------------------------------
3347// Capture screen into an IGraphiBufferProducer
3348// ---------------------------------------------------------------------------
3349
3350/* The code below is here to handle b/8734824
3351 *
3352 * We create a IGraphicBufferProducer wrapper that forwards all calls
3353 * from the surfaceflinger thread to the calling binder thread, where they
3354 * are executed. This allows the calling thread in the calling process to be
3355 * reused and not depend on having "enough" binder threads to handle the
3356 * requests.
3357 */
3358class GraphicProducerWrapper : public BBinder, public MessageHandler {
3359 /* Parts of GraphicProducerWrapper are run on two different threads,
3360 * communicating by sending messages via Looper but also by shared member
3361 * data. Coherence maintenance is subtle and in places implicit (ugh).
3362 *
3363 * Don't rely on Looper's sendMessage/handleMessage providing
3364 * release/acquire semantics for any data not actually in the Message.
3365 * Data going from surfaceflinger to binder threads needs to be
3366 * synchronized explicitly.
3367 *
3368 * Barrier open/wait do provide release/acquire semantics. This provides
3369 * implicit synchronization for data coming back from binder to
3370 * surfaceflinger threads.
3371 */
3372
3373 sp<IGraphicBufferProducer> impl;
3374 sp<Looper> looper;
3375 status_t result;
3376 bool exitPending;
3377 bool exitRequested;
3378 Barrier barrier;
3379 uint32_t code;
3380 Parcel const* data;
3381 Parcel* reply;
3382
3383 enum {
3384 MSG_API_CALL,
3385 MSG_EXIT
3386 };
3387
3388 /*
3389 * Called on surfaceflinger thread. This is called by our "fake"
3390 * BpGraphicBufferProducer. We package the data and reply Parcel and
3391 * forward them to the binder thread.
3392 */
3393 virtual status_t transact(uint32_t code,
3394 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3395 this->code = code;
3396 this->data = &data;
3397 this->reply = reply;
3398 if (exitPending) {
3399 // if we've exited, we run the message synchronously right here.
3400 // note (JH): as far as I can tell from looking at the code, this
3401 // never actually happens. if it does, i'm not sure if it happens
3402 // on the surfaceflinger or binder thread.
3403 handleMessage(Message(MSG_API_CALL));
3404 } else {
3405 barrier.close();
3406 // Prevent stores to this->{code, data, reply} from being
3407 // reordered later than the construction of Message.
3408 atomic_thread_fence(memory_order_release);
3409 looper->sendMessage(this, Message(MSG_API_CALL));
3410 barrier.wait();
3411 }
3412 return result;
3413 }
3414
3415 /*
3416 * here we run on the binder thread. All we've got to do is
3417 * call the real BpGraphicBufferProducer.
3418 */
3419 virtual void handleMessage(const Message& message) {
3420 int what = message.what;
3421 // Prevent reads below from happening before the read from Message
3422 atomic_thread_fence(memory_order_acquire);
3423 if (what == MSG_API_CALL) {
3424 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3425 barrier.open();
3426 } else if (what == MSG_EXIT) {
3427 exitRequested = true;
3428 }
3429 }
3430
3431public:
3432 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3433 : impl(impl),
3434 looper(new Looper(true)),
3435 result(NO_ERROR),
3436 exitPending(false),
3437 exitRequested(false),
3438 code(0),
3439 data(NULL),
3440 reply(NULL)
3441 {}
3442
3443 // Binder thread
3444 status_t waitForResponse() {
3445 do {
3446 looper->pollOnce(-1);
3447 } while (!exitRequested);
3448 return result;
3449 }
3450
3451 // Client thread
3452 void exit(status_t result) {
3453 this->result = result;
3454 exitPending = true;
3455 // Ensure this->result is visible to the binder thread before it
3456 // handles the message.
3457 atomic_thread_fence(memory_order_release);
3458 looper->sendMessage(this, Message(MSG_EXIT));
3459 }
3460};
3461
3462
3463status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3464 const sp<IGraphicBufferProducer>& producer,
3465 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003466 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003467 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3468
3469 if (CC_UNLIKELY(display == 0))
3470 return BAD_VALUE;
3471
3472 if (CC_UNLIKELY(producer == 0))
3473 return BAD_VALUE;
3474
3475 // if we have secure windows on this display, never allow the screen capture
3476 // unless the producer interface is local (i.e.: we can take a screenshot for
3477 // ourselves).
3478 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3479
3480 // Convert to surfaceflinger's internal rotation type.
3481 Transform::orientation_flags rotationFlags;
3482 switch (rotation) {
3483 case ISurfaceComposer::eRotateNone:
3484 rotationFlags = Transform::ROT_0;
3485 break;
3486 case ISurfaceComposer::eRotate90:
3487 rotationFlags = Transform::ROT_90;
3488 break;
3489 case ISurfaceComposer::eRotate180:
3490 rotationFlags = Transform::ROT_180;
3491 break;
3492 case ISurfaceComposer::eRotate270:
3493 rotationFlags = Transform::ROT_270;
3494 break;
3495 default:
3496 rotationFlags = Transform::ROT_0;
3497 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3498 break;
3499 }
3500
3501 class MessageCaptureScreen : public MessageBase {
3502 SurfaceFlinger* flinger;
3503 sp<IBinder> display;
3504 sp<IGraphicBufferProducer> producer;
3505 Rect sourceCrop;
3506 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003507 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003508 bool useIdentityTransform;
3509 Transform::orientation_flags rotation;
3510 status_t result;
3511 bool isLocalScreenshot;
3512 public:
3513 MessageCaptureScreen(SurfaceFlinger* flinger,
3514 const sp<IBinder>& display,
3515 const sp<IGraphicBufferProducer>& producer,
3516 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003517 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003518 bool useIdentityTransform,
3519 Transform::orientation_flags rotation,
3520 bool isLocalScreenshot)
3521 : flinger(flinger), display(display), producer(producer),
3522 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3523 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3524 useIdentityTransform(useIdentityTransform),
3525 rotation(rotation), result(PERMISSION_DENIED),
3526 isLocalScreenshot(isLocalScreenshot)
3527 {
3528 }
3529 status_t getResult() const {
3530 return result;
3531 }
3532 virtual bool handler() {
3533 Mutex::Autolock _l(flinger->mStateLock);
3534 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3535 result = flinger->captureScreenImplLocked(hw, producer,
3536 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3537 useIdentityTransform, rotation, isLocalScreenshot);
3538 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3539 return true;
3540 }
3541 };
3542
3543 // this creates a "fake" BBinder which will serve as a "fake" remote
3544 // binder to receive the marshaled calls and forward them to the
3545 // real remote (a BpGraphicBufferProducer)
3546 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3547
3548 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3549 // which does the marshaling work forwards to our "fake remote" above.
3550 sp<MessageBase> msg = new MessageCaptureScreen(this,
3551 display, IGraphicBufferProducer::asInterface( wrapper ),
3552 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3553 useIdentityTransform, rotationFlags, isLocalScreenshot);
3554
3555 status_t res = postMessageAsync(msg);
3556 if (res == NO_ERROR) {
3557 res = wrapper->waitForResponse();
3558 }
3559 return res;
3560}
3561
3562
3563void SurfaceFlinger::renderScreenImplLocked(
3564 const sp<const DisplayDevice>& hw,
3565 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003566 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003567 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3568{
3569 ATRACE_CALL();
3570 RenderEngine& engine(getRenderEngine());
3571
3572 // get screen geometry
3573 const int32_t hw_w = hw->getWidth();
3574 const int32_t hw_h = hw->getHeight();
3575 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3576 static_cast<int32_t>(reqHeight) != hw_h;
3577
3578 // if a default or invalid sourceCrop is passed in, set reasonable values
3579 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3580 !sourceCrop.isValid()) {
3581 sourceCrop.setLeftTop(Point(0, 0));
3582 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3583 }
3584
3585 // ensure that sourceCrop is inside screen
3586 if (sourceCrop.left < 0) {
3587 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3588 }
3589 if (sourceCrop.right > hw_w) {
3590 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3591 }
3592 if (sourceCrop.top < 0) {
3593 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3594 }
3595 if (sourceCrop.bottom > hw_h) {
3596 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3597 }
3598
3599 // make sure to clear all GL error flags
3600 engine.checkErrors();
3601
3602 // set-up our viewport
3603 engine.setViewportAndProjection(
3604 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3605 engine.disableTexturing();
3606
3607 // redraw the screen entirely...
3608 engine.clearWithColor(0, 0, 0, 1);
3609
Robert Carr1f0a16a2016-10-24 16:27:39 -07003610 // We loop through the first level of layers without traversing,
3611 // as we need to interpret min/max layer Z in the top level Z space.
3612 for (const auto& layer : mDrawingState.layersSortedByZ) {
3613 if (layer->getLayerStack() != hw->getLayerStack()) {
3614 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003615 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003616 const Layer::State& state(layer->getDrawingState());
3617 if (state.z < minLayerZ || state.z > maxLayerZ) {
3618 continue;
3619 }
3620 layer->traverseInZOrder([&](Layer* layer) {
3621 if (!layer->isVisible()) {
3622 return;
3623 }
3624 if (filtering) layer->setFiltering(true);
3625 layer->draw(hw, useIdentityTransform);
3626 if (filtering) layer->setFiltering(false);
3627 });
3628 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003629
3630 // compositionComplete is needed for older driver
3631 hw->compositionComplete();
3632 hw->setViewportAndProjection();
3633}
3634
3635
3636status_t SurfaceFlinger::captureScreenImplLocked(
3637 const sp<const DisplayDevice>& hw,
3638 const sp<IGraphicBufferProducer>& producer,
3639 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003640 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003641 bool useIdentityTransform, Transform::orientation_flags rotation,
3642 bool isLocalScreenshot)
3643{
3644 ATRACE_CALL();
3645
3646 // get screen geometry
3647 uint32_t hw_w = hw->getWidth();
3648 uint32_t hw_h = hw->getHeight();
3649
3650 if (rotation & Transform::ROT_90) {
3651 std::swap(hw_w, hw_h);
3652 }
3653
3654 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3655 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3656 reqWidth, reqHeight, hw_w, hw_h);
3657 return BAD_VALUE;
3658 }
3659
3660 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3661 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3662
3663 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003664 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003665 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003666 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3667 (state.z < minLayerZ || state.z > maxLayerZ)) {
3668 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003669 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003670 layer->traverseInZOrder([&](Layer *layer) {
3671 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3672 layer->isSecure());
3673 });
3674 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003675
3676 if (!isLocalScreenshot && secureLayerIsVisible) {
3677 ALOGW("FB is protected: PERMISSION_DENIED");
3678 return PERMISSION_DENIED;
3679 }
3680
3681 // create a surface (because we're a producer, and we need to
3682 // dequeue/queue a buffer)
3683 sp<Surface> sur = new Surface(producer, false);
3684 ANativeWindow* window = sur.get();
3685
3686 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3687 if (result == NO_ERROR) {
3688 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3689 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3690
3691 int err = 0;
3692 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3693 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3694 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3695 err |= native_window_set_usage(window, usage);
3696
3697 if (err == NO_ERROR) {
3698 ANativeWindowBuffer* buffer;
3699 /* TODO: Once we have the sync framework everywhere this can use
3700 * server-side waits on the fence that dequeueBuffer returns.
3701 */
3702 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3703 if (result == NO_ERROR) {
3704 int syncFd = -1;
3705 // create an EGLImage from the buffer so we can later
3706 // turn it into a texture
3707 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3708 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3709 if (image != EGL_NO_IMAGE_KHR) {
3710 // this binds the given EGLImage as a framebuffer for the
3711 // duration of this scope.
3712 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3713 if (imageBond.getStatus() == NO_ERROR) {
3714 // this will in fact render into our dequeued buffer
3715 // via an FBO, which means we didn't have to create
3716 // an EGLSurface and therefore we're not
3717 // dependent on the context's EGLConfig.
3718 renderScreenImplLocked(
3719 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3720 useIdentityTransform, rotation);
3721
3722 // Attempt to create a sync khr object that can produce a sync point. If that
3723 // isn't available, create a non-dupable sync object in the fallback path and
3724 // wait on it directly.
3725 EGLSyncKHR sync;
3726 if (!DEBUG_SCREENSHOTS) {
3727 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3728 // native fence fd will not be populated until flush() is done.
3729 getRenderEngine().flush();
3730 } else {
3731 sync = EGL_NO_SYNC_KHR;
3732 }
3733 if (sync != EGL_NO_SYNC_KHR) {
3734 // get the sync fd
3735 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3736 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3737 ALOGW("captureScreen: failed to dup sync khr object");
3738 syncFd = -1;
3739 }
3740 eglDestroySyncKHR(mEGLDisplay, sync);
3741 } else {
3742 // fallback path
3743 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3744 if (sync != EGL_NO_SYNC_KHR) {
3745 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3746 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3747 EGLint eglErr = eglGetError();
3748 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3749 ALOGW("captureScreen: fence wait timed out");
3750 } else {
3751 ALOGW_IF(eglErr != EGL_SUCCESS,
3752 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3753 }
3754 eglDestroySyncKHR(mEGLDisplay, sync);
3755 } else {
3756 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3757 }
3758 }
3759 if (DEBUG_SCREENSHOTS) {
3760 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3761 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3762 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3763 hw, minLayerZ, maxLayerZ);
3764 delete [] pixels;
3765 }
3766
3767 } else {
3768 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3769 result = INVALID_OPERATION;
3770 window->cancelBuffer(window, buffer, syncFd);
3771 buffer = NULL;
3772 }
3773 // destroy our image
3774 eglDestroyImageKHR(mEGLDisplay, image);
3775 } else {
3776 result = BAD_VALUE;
3777 }
3778 if (buffer) {
3779 // queueBuffer takes ownership of syncFd
3780 result = window->queueBuffer(window, buffer, syncFd);
3781 }
3782 }
3783 } else {
3784 result = BAD_VALUE;
3785 }
3786 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3787 }
3788
3789 return result;
3790}
3791
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003792void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003793 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003794 if (DEBUG_SCREENSHOTS) {
3795 for (size_t y=0 ; y<h ; y++) {
3796 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3797 for (size_t x=0 ; x<w ; x++) {
3798 if (p[x] != 0xFF000000) return;
3799 }
3800 }
3801 ALOGE("*** we just took a black screenshot ***\n"
3802 "requested minz=%d, maxz=%d, layerStack=%d",
3803 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003804 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003805 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003806 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003807 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3808 state.z <= maxLayerZ) {
3809 layer->traverseInZOrder([&](Layer* layer) {
3810 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3811 layer->isVisible() ? '+' : '-',
3812 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003813 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003814 i++;
3815 });
3816 }
3817 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003818 }
3819}
3820
3821// ---------------------------------------------------------------------------
3822
Robert Carr2047fae2016-11-28 14:09:09 -08003823void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3824 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003825}
3826
Robert Carr2047fae2016-11-28 14:09:09 -08003827void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3828 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003829}
3830
3831}; // namespace android
3832
3833
3834#if defined(__gl_h_)
3835#error "don't include gl/gl.h in this file"
3836#endif
3837
3838#if defined(__gl2_h_)
3839#error "don't include gl2/gl2.h in this file"
3840#endif