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