blob: 2cd02a09195f65b1111ac641723af4c39586d7f6 [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,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002518 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
2519 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
Robert Carr1f0a16a2016-10-24 16:27:39 -07002551 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002552 if (result != NO_ERROR) {
2553 return result;
2554 }
2555 mInterceptor.saveSurfaceCreation(layer);
2556
2557 setTransactionFlags(eTransactionNeeded);
2558 return result;
2559}
2560
2561status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2562 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2563 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2564{
2565 // initialize the surfaces
2566 switch (format) {
2567 case PIXEL_FORMAT_TRANSPARENT:
2568 case PIXEL_FORMAT_TRANSLUCENT:
2569 format = PIXEL_FORMAT_RGBA_8888;
2570 break;
2571 case PIXEL_FORMAT_OPAQUE:
2572 format = PIXEL_FORMAT_RGBX_8888;
2573 break;
2574 }
2575
2576 *outLayer = new Layer(this, client, name, w, h, flags);
2577 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2578 if (err == NO_ERROR) {
2579 *handle = (*outLayer)->getHandle();
2580 *gbp = (*outLayer)->getProducer();
2581 }
2582
2583 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2584 return err;
2585}
2586
2587status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2588 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2589 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2590{
2591 *outLayer = new LayerDim(this, client, name, w, h, flags);
2592 *handle = (*outLayer)->getHandle();
2593 *gbp = (*outLayer)->getProducer();
2594 return NO_ERROR;
2595}
2596
2597status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2598{
2599 // called by the window manager when it wants to remove a Layer
2600 status_t err = NO_ERROR;
2601 sp<Layer> l(client->getLayerUser(handle));
2602 if (l != NULL) {
2603 mInterceptor.saveSurfaceDeletion(l);
2604 err = removeLayer(l);
2605 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2606 "error removing layer=%p (%s)", l.get(), strerror(-err));
2607 }
2608 return err;
2609}
2610
2611status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2612{
2613 // called by ~LayerCleaner() when all references to the IBinder (handle)
2614 // are gone
2615 return removeLayer(layer);
2616}
2617
2618// ---------------------------------------------------------------------------
2619
2620void SurfaceFlinger::onInitializeDisplays() {
2621 // reset screen orientation and use primary layer stack
2622 Vector<ComposerState> state;
2623 Vector<DisplayState> displays;
2624 DisplayState d;
2625 d.what = DisplayState::eDisplayProjectionChanged |
2626 DisplayState::eLayerStackChanged;
2627 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2628 d.layerStack = 0;
2629 d.orientation = DisplayState::eOrientationDefault;
2630 d.frame.makeInvalid();
2631 d.viewport.makeInvalid();
2632 d.width = 0;
2633 d.height = 0;
2634 displays.add(d);
2635 setTransactionState(state, displays, 0);
2636 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2637
2638 const nsecs_t period =
2639 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2640 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2641}
2642
2643void SurfaceFlinger::initializeDisplays() {
2644 class MessageScreenInitialized : public MessageBase {
2645 SurfaceFlinger* flinger;
2646 public:
2647 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2648 virtual bool handler() {
2649 flinger->onInitializeDisplays();
2650 return true;
2651 }
2652 };
2653 sp<MessageBase> msg = new MessageScreenInitialized(this);
2654 postMessageAsync(msg); // we may be called from main thread, use async message
2655}
2656
2657void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2658 int mode) {
2659 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2660 this);
2661 int32_t type = hw->getDisplayType();
2662 int currentMode = hw->getPowerMode();
2663
2664 if (mode == currentMode) {
2665 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2666 return;
2667 }
2668
2669 hw->setPowerMode(mode);
2670 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2671 ALOGW("Trying to set power mode for virtual display");
2672 return;
2673 }
2674
2675 if (mInterceptor.isEnabled()) {
2676 Mutex::Autolock _l(mStateLock);
2677 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2678 if (idx < 0) {
2679 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2680 return;
2681 }
2682 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2683 }
2684
2685 if (currentMode == HWC_POWER_MODE_OFF) {
2686 // Turn on the display
2687 getHwComposer().setPowerMode(type, mode);
2688 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2689 // FIXME: eventthread only knows about the main display right now
2690 mEventThread->onScreenAcquired();
2691 resyncToHardwareVsync(true);
2692 }
2693
2694 mVisibleRegionsDirty = true;
2695 mHasPoweredOff = true;
2696 repaintEverything();
2697
2698 struct sched_param param = {0};
2699 param.sched_priority = 1;
2700 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2701 ALOGW("Couldn't set SCHED_FIFO on display on");
2702 }
2703 } else if (mode == HWC_POWER_MODE_OFF) {
2704 // Turn off the display
2705 struct sched_param param = {0};
2706 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2707 ALOGW("Couldn't set SCHED_OTHER on display off");
2708 }
2709
2710 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2711 disableHardwareVsync(true); // also cancels any in-progress resync
2712
2713 // FIXME: eventthread only knows about the main display right now
2714 mEventThread->onScreenReleased();
2715 }
2716
2717 getHwComposer().setPowerMode(type, mode);
2718 mVisibleRegionsDirty = true;
2719 // from this point on, SF will stop drawing on this display
2720 } else {
2721 getHwComposer().setPowerMode(type, mode);
2722 }
2723}
2724
2725void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2726 class MessageSetPowerMode: public MessageBase {
2727 SurfaceFlinger& mFlinger;
2728 sp<IBinder> mDisplay;
2729 int mMode;
2730 public:
2731 MessageSetPowerMode(SurfaceFlinger& flinger,
2732 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2733 mDisplay(disp) { mMode = mode; }
2734 virtual bool handler() {
2735 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2736 if (hw == NULL) {
2737 ALOGE("Attempt to set power mode = %d for null display %p",
2738 mMode, mDisplay.get());
2739 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2740 ALOGW("Attempt to set power mode = %d for virtual display",
2741 mMode);
2742 } else {
2743 mFlinger.setPowerModeInternal(hw, mMode);
2744 }
2745 return true;
2746 }
2747 };
2748 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2749 postMessageSync(msg);
2750}
2751
2752// ---------------------------------------------------------------------------
2753
2754status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2755{
2756 String8 result;
2757
2758 IPCThreadState* ipc = IPCThreadState::self();
2759 const int pid = ipc->getCallingPid();
2760 const int uid = ipc->getCallingUid();
2761 if ((uid != AID_SHELL) &&
2762 !PermissionCache::checkPermission(sDump, pid, uid)) {
2763 result.appendFormat("Permission Denial: "
2764 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2765 } else {
2766 // Try to get the main lock, but give up after one second
2767 // (this would indicate SF is stuck, but we want to be able to
2768 // print something in dumpsys).
2769 status_t err = mStateLock.timedLock(s2ns(1));
2770 bool locked = (err == NO_ERROR);
2771 if (!locked) {
2772 result.appendFormat(
2773 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2774 "dumping anyways (no locks held)\n", strerror(-err), err);
2775 }
2776
2777 bool dumpAll = true;
2778 size_t index = 0;
2779 size_t numArgs = args.size();
2780 if (numArgs) {
2781 if ((index < numArgs) &&
2782 (args[index] == String16("--list"))) {
2783 index++;
2784 listLayersLocked(args, index, result);
2785 dumpAll = false;
2786 }
2787
2788 if ((index < numArgs) &&
2789 (args[index] == String16("--latency"))) {
2790 index++;
2791 dumpStatsLocked(args, index, result);
2792 dumpAll = false;
2793 }
2794
2795 if ((index < numArgs) &&
2796 (args[index] == String16("--latency-clear"))) {
2797 index++;
2798 clearStatsLocked(args, index, result);
2799 dumpAll = false;
2800 }
2801
2802 if ((index < numArgs) &&
2803 (args[index] == String16("--dispsync"))) {
2804 index++;
2805 mPrimaryDispSync.dump(result);
2806 dumpAll = false;
2807 }
2808
2809 if ((index < numArgs) &&
2810 (args[index] == String16("--static-screen"))) {
2811 index++;
2812 dumpStaticScreenStats(result);
2813 dumpAll = false;
2814 }
2815
2816 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002817 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002818 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002819 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002820 dumpAll = false;
2821 }
2822 }
2823
2824 if (dumpAll) {
2825 dumpAllLocked(args, index, result);
2826 }
2827
2828 if (locked) {
2829 mStateLock.unlock();
2830 }
2831 }
2832 write(fd, result.string(), result.size());
2833 return NO_ERROR;
2834}
2835
2836void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2837 size_t& /* index */, String8& result) const
2838{
Robert Carr2047fae2016-11-28 14:09:09 -08002839 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002840 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002841 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002842}
2843
2844void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2845 String8& result) const
2846{
2847 String8 name;
2848 if (index < args.size()) {
2849 name = String8(args[index]);
2850 index++;
2851 }
2852
2853 const nsecs_t period =
2854 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2855 result.appendFormat("%" PRId64 "\n", period);
2856
2857 if (name.isEmpty()) {
2858 mAnimFrameTracker.dumpStats(result);
2859 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002860 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002861 if (name == layer->getName()) {
2862 layer->dumpFrameStats(result);
2863 }
Robert Carr2047fae2016-11-28 14:09:09 -08002864 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002865 }
2866}
2867
2868void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2869 String8& /* result */)
2870{
2871 String8 name;
2872 if (index < args.size()) {
2873 name = String8(args[index]);
2874 index++;
2875 }
2876
Robert Carr2047fae2016-11-28 14:09:09 -08002877 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002878 if (name.isEmpty() || (name == layer->getName())) {
2879 layer->clearFrameStats();
2880 }
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002882
2883 mAnimFrameTracker.clearStats();
2884}
2885
2886// This should only be called from the main thread. Otherwise it would need
2887// the lock and should use mCurrentState rather than mDrawingState.
2888void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002889 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002890 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002891 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002892
2893 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2894}
2895
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002896void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002897{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002898 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002899#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002900 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002901#endif
2902#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002903 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002904#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002905 if (isLayerTripleBufferingDisabled())
2906 result.append(" DISABLE_TRIPLE_BUFFERING");
2907 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002908}
2909
2910void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2911{
2912 result.appendFormat("Static screen stats:\n");
2913 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2914 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2915 float percent = 100.0f *
2916 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2917 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2918 b + 1, bucketTimeSec, percent);
2919 }
2920 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2921 float percent = 100.0f *
2922 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2923 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2924 NUM_BUCKETS - 1, bucketTimeSec, percent);
2925}
2926
Brian Andersond6927fb2016-07-23 23:37:30 -07002927void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
2928 result.appendFormat("Layer frame timestamps:\n");
2929
2930 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2931 const size_t count = currentLayers.size();
2932 for (size_t i=0 ; i<count ; i++) {
2933 currentLayers[i]->dumpFrameEvents(result);
2934 }
2935}
2936
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002937void SurfaceFlinger::recordBufferingStats(const char* layerName,
2938 std::vector<OccupancyTracker::Segment>&& history) {
2939 Mutex::Autolock lock(mBufferingStatsMutex);
2940 auto& stats = mBufferingStats[layerName];
2941 for (const auto& segment : history) {
2942 if (!segment.usedThirdBuffer) {
2943 stats.twoBufferTime += segment.totalTime;
2944 }
2945 if (segment.occupancyAverage < 1.0f) {
2946 stats.doubleBufferedTime += segment.totalTime;
2947 } else if (segment.occupancyAverage < 2.0f) {
2948 stats.tripleBufferedTime += segment.totalTime;
2949 }
2950 ++stats.numSegments;
2951 stats.totalTime += segment.totalTime;
2952 }
2953}
2954
2955void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2956 result.append("Buffering stats:\n");
2957 result.append(" [Layer name] <Active time> <Two buffer> "
2958 "<Double buffered> <Triple buffered>\n");
2959 Mutex::Autolock lock(mBufferingStatsMutex);
2960 typedef std::tuple<std::string, float, float, float> BufferTuple;
2961 std::map<float, BufferTuple, std::greater<float>> sorted;
2962 for (const auto& statsPair : mBufferingStats) {
2963 const char* name = statsPair.first.c_str();
2964 const BufferingStats& stats = statsPair.second;
2965 if (stats.numSegments == 0) {
2966 continue;
2967 }
2968 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2969 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2970 stats.totalTime;
2971 float doubleBufferRatio = static_cast<float>(
2972 stats.doubleBufferedTime) / stats.totalTime;
2973 float tripleBufferRatio = static_cast<float>(
2974 stats.tripleBufferedTime) / stats.totalTime;
2975 sorted.insert({activeTime, {name, twoBufferRatio,
2976 doubleBufferRatio, tripleBufferRatio}});
2977 }
2978 for (const auto& sortedPair : sorted) {
2979 float activeTime = sortedPair.first;
2980 const BufferTuple& values = sortedPair.second;
2981 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2982 std::get<0>(values).c_str(), activeTime,
2983 std::get<1>(values), std::get<2>(values),
2984 std::get<3>(values));
2985 }
2986 result.append("\n");
2987}
2988
2989void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2990 String8& result) const
2991{
2992 bool colorize = false;
2993 if (index < args.size()
2994 && (args[index] == String16("--color"))) {
2995 colorize = true;
2996 index++;
2997 }
2998
2999 Colorizer colorizer(colorize);
3000
3001 // figure out if we're stuck somewhere
3002 const nsecs_t now = systemTime();
3003 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3004 const nsecs_t inTransaction(mDebugInTransaction);
3005 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3006 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3007
3008 /*
3009 * Dump library configuration.
3010 */
3011
3012 colorizer.bold(result);
3013 result.append("Build configuration:");
3014 colorizer.reset(result);
3015 appendSfConfigString(result);
3016 appendUiConfigString(result);
3017 appendGuiConfigString(result);
3018 result.append("\n");
3019
3020 colorizer.bold(result);
3021 result.append("Sync configuration: ");
3022 colorizer.reset(result);
3023 result.append(SyncFeatures::getInstance().toString());
3024 result.append("\n");
3025
3026 colorizer.bold(result);
3027 result.append("DispSync configuration: ");
3028 colorizer.reset(result);
3029 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3030 "present offset %d ns (refresh %" PRId64 " ns)",
3031 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3032 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3033 result.append("\n");
3034
3035 // Dump static screen stats
3036 result.append("\n");
3037 dumpStaticScreenStats(result);
3038 result.append("\n");
3039
3040 dumpBufferingStats(result);
3041
3042 /*
3043 * Dump the visible layer list
3044 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003045 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003047 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003048 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003049 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003050 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003051
3052 /*
3053 * Dump Display state
3054 */
3055
3056 colorizer.bold(result);
3057 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3058 colorizer.reset(result);
3059 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3060 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3061 hw->dump(result);
3062 }
3063
3064 /*
3065 * Dump SurfaceFlinger global state
3066 */
3067
3068 colorizer.bold(result);
3069 result.append("SurfaceFlinger global state:\n");
3070 colorizer.reset(result);
3071
3072 HWComposer& hwc(getHwComposer());
3073 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3074
3075 colorizer.bold(result);
3076 result.appendFormat("EGL implementation : %s\n",
3077 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3078 colorizer.reset(result);
3079 result.appendFormat("%s\n",
3080 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3081
3082 mRenderEngine->dump(result);
3083
3084 hw->undefinedRegion.dump(result, "undefinedRegion");
3085 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3086 hw->getOrientation(), hw->isDisplayOn());
3087 result.appendFormat(
3088 " last eglSwapBuffers() time: %f us\n"
3089 " last transaction time : %f us\n"
3090 " transaction-flags : %08x\n"
3091 " refresh-rate : %f fps\n"
3092 " x-dpi : %f\n"
3093 " y-dpi : %f\n"
3094 " gpu_to_cpu_unsupported : %d\n"
3095 ,
3096 mLastSwapBufferTime/1000.0,
3097 mLastTransactionTime/1000.0,
3098 mTransactionFlags,
3099 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3100 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3101 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3102 !mGpuToCpuSupported);
3103
3104 result.appendFormat(" eglSwapBuffers time: %f us\n",
3105 inSwapBuffersDuration/1000.0);
3106
3107 result.appendFormat(" transaction time: %f us\n",
3108 inTransactionDuration/1000.0);
3109
3110 /*
3111 * VSYNC state
3112 */
3113 mEventThread->dump(result);
3114
3115 /*
3116 * Dump HWComposer state
3117 */
3118 colorizer.bold(result);
3119 result.append("h/w composer state:\n");
3120 colorizer.reset(result);
3121 result.appendFormat(" h/w composer %s and %s\n",
3122 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3123 (mDebugDisableHWC || mDebugRegion || mDaltonize
3124 || mHasColorMatrix) ? "disabled" : "enabled");
3125 hwc.dump(result);
3126
3127 /*
3128 * Dump gralloc state
3129 */
3130 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3131 alloc.dump(result);
3132}
3133
3134const Vector< sp<Layer> >&
3135SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3136 // Note: mStateLock is held here
3137 wp<IBinder> dpy;
3138 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3139 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3140 dpy = mDisplays.keyAt(i);
3141 break;
3142 }
3143 }
3144 if (dpy == NULL) {
3145 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3146 // Just use the primary display so we have something to return
3147 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3148 }
3149 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3150}
3151
3152bool SurfaceFlinger::startDdmConnection()
3153{
3154 void* libddmconnection_dso =
3155 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3156 if (!libddmconnection_dso) {
3157 return false;
3158 }
3159 void (*DdmConnection_start)(const char* name);
3160 DdmConnection_start =
3161 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3162 if (!DdmConnection_start) {
3163 dlclose(libddmconnection_dso);
3164 return false;
3165 }
3166 (*DdmConnection_start)(getServiceName());
3167 return true;
3168}
3169
3170status_t SurfaceFlinger::onTransact(
3171 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3172{
3173 switch (code) {
3174 case CREATE_CONNECTION:
3175 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003176 case BOOT_FINISHED:
3177 case CLEAR_ANIMATION_FRAME_STATS:
3178 case GET_ANIMATION_FRAME_STATS:
3179 case SET_POWER_MODE:
3180 case GET_HDR_CAPABILITIES:
3181 {
3182 // codes that require permission check
3183 IPCThreadState* ipc = IPCThreadState::self();
3184 const int pid = ipc->getCallingPid();
3185 const int uid = ipc->getCallingUid();
3186 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3187 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3188 ALOGE("Permission Denial: "
3189 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3190 return PERMISSION_DENIED;
3191 }
3192 break;
3193 }
Robert Carr1db73f62016-12-21 12:58:51 -08003194 /*
3195 * Calling setTransactionState is safe, because you need to have been
3196 * granted a reference to Client* and Handle* to do anything with it.
3197 *
3198 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3199 */
3200 case SET_TRANSACTION_STATE:
3201 case CREATE_SCOPED_CONNECTION:
3202 {
3203 break;
3204 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003205 case CAPTURE_SCREEN:
3206 {
3207 // codes that require permission check
3208 IPCThreadState* ipc = IPCThreadState::self();
3209 const int pid = ipc->getCallingPid();
3210 const int uid = ipc->getCallingUid();
3211 if ((uid != AID_GRAPHICS) &&
3212 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3213 ALOGE("Permission Denial: "
3214 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3215 return PERMISSION_DENIED;
3216 }
3217 break;
3218 }
3219 }
3220
3221 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3222 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3223 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3224 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3225 IPCThreadState* ipc = IPCThreadState::self();
3226 const int pid = ipc->getCallingPid();
3227 const int uid = ipc->getCallingUid();
3228 ALOGE("Permission Denial: "
3229 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3230 return PERMISSION_DENIED;
3231 }
3232 int n;
3233 switch (code) {
3234 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3235 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3236 return NO_ERROR;
3237 case 1002: // SHOW_UPDATES
3238 n = data.readInt32();
3239 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3240 invalidateHwcGeometry();
3241 repaintEverything();
3242 return NO_ERROR;
3243 case 1004:{ // repaint everything
3244 repaintEverything();
3245 return NO_ERROR;
3246 }
3247 case 1005:{ // force transaction
3248 setTransactionFlags(
3249 eTransactionNeeded|
3250 eDisplayTransactionNeeded|
3251 eTraversalNeeded);
3252 return NO_ERROR;
3253 }
3254 case 1006:{ // send empty update
3255 signalRefresh();
3256 return NO_ERROR;
3257 }
3258 case 1008: // toggle use of hw composer
3259 n = data.readInt32();
3260 mDebugDisableHWC = n ? 1 : 0;
3261 invalidateHwcGeometry();
3262 repaintEverything();
3263 return NO_ERROR;
3264 case 1009: // toggle use of transform hint
3265 n = data.readInt32();
3266 mDebugDisableTransformHint = n ? 1 : 0;
3267 invalidateHwcGeometry();
3268 repaintEverything();
3269 return NO_ERROR;
3270 case 1010: // interrogate.
3271 reply->writeInt32(0);
3272 reply->writeInt32(0);
3273 reply->writeInt32(mDebugRegion);
3274 reply->writeInt32(0);
3275 reply->writeInt32(mDebugDisableHWC);
3276 return NO_ERROR;
3277 case 1013: {
3278 Mutex::Autolock _l(mStateLock);
3279 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3280 reply->writeInt32(hw->getPageFlipCount());
3281 return NO_ERROR;
3282 }
3283 case 1014: {
3284 // daltonize
3285 n = data.readInt32();
3286 switch (n % 10) {
3287 case 1:
3288 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3289 break;
3290 case 2:
3291 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3292 break;
3293 case 3:
3294 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3295 break;
3296 }
3297 if (n >= 10) {
3298 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3299 } else {
3300 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3301 }
3302 mDaltonize = n > 0;
3303 invalidateHwcGeometry();
3304 repaintEverything();
3305 return NO_ERROR;
3306 }
3307 case 1015: {
3308 // apply a color matrix
3309 n = data.readInt32();
3310 mHasColorMatrix = n ? 1 : 0;
3311 if (n) {
3312 // color matrix is sent as mat3 matrix followed by vec3
3313 // offset, then packed into a mat4 where the last row is
3314 // the offset and extra values are 0
3315 for (size_t i = 0 ; i < 4; i++) {
3316 for (size_t j = 0; j < 4; j++) {
3317 mColorMatrix[i][j] = data.readFloat();
3318 }
3319 }
3320 } else {
3321 mColorMatrix = mat4();
3322 }
3323 invalidateHwcGeometry();
3324 repaintEverything();
3325 return NO_ERROR;
3326 }
3327 // This is an experimental interface
3328 // Needs to be shifted to proper binder interface when we productize
3329 case 1016: {
3330 n = data.readInt32();
3331 mPrimaryDispSync.setRefreshSkipCount(n);
3332 return NO_ERROR;
3333 }
3334 case 1017: {
3335 n = data.readInt32();
3336 mForceFullDamage = static_cast<bool>(n);
3337 return NO_ERROR;
3338 }
3339 case 1018: { // Modify Choreographer's phase offset
3340 n = data.readInt32();
3341 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3342 return NO_ERROR;
3343 }
3344 case 1019: { // Modify SurfaceFlinger's phase offset
3345 n = data.readInt32();
3346 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3347 return NO_ERROR;
3348 }
3349 case 1020: { // Layer updates interceptor
3350 n = data.readInt32();
3351 if (n) {
3352 ALOGV("Interceptor enabled");
3353 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3354 }
3355 else{
3356 ALOGV("Interceptor disabled");
3357 mInterceptor.disable();
3358 }
3359 return NO_ERROR;
3360 }
3361 case 1021: { // Disable HWC virtual displays
3362 n = data.readInt32();
3363 mUseHwcVirtualDisplays = !n;
3364 return NO_ERROR;
3365 }
3366 }
3367 }
3368 return err;
3369}
3370
3371void SurfaceFlinger::repaintEverything() {
3372 android_atomic_or(1, &mRepaintEverything);
3373 signalTransaction();
3374}
3375
3376// ---------------------------------------------------------------------------
3377// Capture screen into an IGraphiBufferProducer
3378// ---------------------------------------------------------------------------
3379
3380/* The code below is here to handle b/8734824
3381 *
3382 * We create a IGraphicBufferProducer wrapper that forwards all calls
3383 * from the surfaceflinger thread to the calling binder thread, where they
3384 * are executed. This allows the calling thread in the calling process to be
3385 * reused and not depend on having "enough" binder threads to handle the
3386 * requests.
3387 */
3388class GraphicProducerWrapper : public BBinder, public MessageHandler {
3389 /* Parts of GraphicProducerWrapper are run on two different threads,
3390 * communicating by sending messages via Looper but also by shared member
3391 * data. Coherence maintenance is subtle and in places implicit (ugh).
3392 *
3393 * Don't rely on Looper's sendMessage/handleMessage providing
3394 * release/acquire semantics for any data not actually in the Message.
3395 * Data going from surfaceflinger to binder threads needs to be
3396 * synchronized explicitly.
3397 *
3398 * Barrier open/wait do provide release/acquire semantics. This provides
3399 * implicit synchronization for data coming back from binder to
3400 * surfaceflinger threads.
3401 */
3402
3403 sp<IGraphicBufferProducer> impl;
3404 sp<Looper> looper;
3405 status_t result;
3406 bool exitPending;
3407 bool exitRequested;
3408 Barrier barrier;
3409 uint32_t code;
3410 Parcel const* data;
3411 Parcel* reply;
3412
3413 enum {
3414 MSG_API_CALL,
3415 MSG_EXIT
3416 };
3417
3418 /*
3419 * Called on surfaceflinger thread. This is called by our "fake"
3420 * BpGraphicBufferProducer. We package the data and reply Parcel and
3421 * forward them to the binder thread.
3422 */
3423 virtual status_t transact(uint32_t code,
3424 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3425 this->code = code;
3426 this->data = &data;
3427 this->reply = reply;
3428 if (exitPending) {
3429 // if we've exited, we run the message synchronously right here.
3430 // note (JH): as far as I can tell from looking at the code, this
3431 // never actually happens. if it does, i'm not sure if it happens
3432 // on the surfaceflinger or binder thread.
3433 handleMessage(Message(MSG_API_CALL));
3434 } else {
3435 barrier.close();
3436 // Prevent stores to this->{code, data, reply} from being
3437 // reordered later than the construction of Message.
3438 atomic_thread_fence(memory_order_release);
3439 looper->sendMessage(this, Message(MSG_API_CALL));
3440 barrier.wait();
3441 }
3442 return result;
3443 }
3444
3445 /*
3446 * here we run on the binder thread. All we've got to do is
3447 * call the real BpGraphicBufferProducer.
3448 */
3449 virtual void handleMessage(const Message& message) {
3450 int what = message.what;
3451 // Prevent reads below from happening before the read from Message
3452 atomic_thread_fence(memory_order_acquire);
3453 if (what == MSG_API_CALL) {
3454 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3455 barrier.open();
3456 } else if (what == MSG_EXIT) {
3457 exitRequested = true;
3458 }
3459 }
3460
3461public:
3462 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3463 : impl(impl),
3464 looper(new Looper(true)),
3465 result(NO_ERROR),
3466 exitPending(false),
3467 exitRequested(false),
3468 code(0),
3469 data(NULL),
3470 reply(NULL)
3471 {}
3472
3473 // Binder thread
3474 status_t waitForResponse() {
3475 do {
3476 looper->pollOnce(-1);
3477 } while (!exitRequested);
3478 return result;
3479 }
3480
3481 // Client thread
3482 void exit(status_t result) {
3483 this->result = result;
3484 exitPending = true;
3485 // Ensure this->result is visible to the binder thread before it
3486 // handles the message.
3487 atomic_thread_fence(memory_order_release);
3488 looper->sendMessage(this, Message(MSG_EXIT));
3489 }
3490};
3491
3492
3493status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3494 const sp<IGraphicBufferProducer>& producer,
3495 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003496 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003497 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3498
3499 if (CC_UNLIKELY(display == 0))
3500 return BAD_VALUE;
3501
3502 if (CC_UNLIKELY(producer == 0))
3503 return BAD_VALUE;
3504
3505 // if we have secure windows on this display, never allow the screen capture
3506 // unless the producer interface is local (i.e.: we can take a screenshot for
3507 // ourselves).
3508 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3509
3510 // Convert to surfaceflinger's internal rotation type.
3511 Transform::orientation_flags rotationFlags;
3512 switch (rotation) {
3513 case ISurfaceComposer::eRotateNone:
3514 rotationFlags = Transform::ROT_0;
3515 break;
3516 case ISurfaceComposer::eRotate90:
3517 rotationFlags = Transform::ROT_90;
3518 break;
3519 case ISurfaceComposer::eRotate180:
3520 rotationFlags = Transform::ROT_180;
3521 break;
3522 case ISurfaceComposer::eRotate270:
3523 rotationFlags = Transform::ROT_270;
3524 break;
3525 default:
3526 rotationFlags = Transform::ROT_0;
3527 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3528 break;
3529 }
3530
3531 class MessageCaptureScreen : public MessageBase {
3532 SurfaceFlinger* flinger;
3533 sp<IBinder> display;
3534 sp<IGraphicBufferProducer> producer;
3535 Rect sourceCrop;
3536 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003537 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003538 bool useIdentityTransform;
3539 Transform::orientation_flags rotation;
3540 status_t result;
3541 bool isLocalScreenshot;
3542 public:
3543 MessageCaptureScreen(SurfaceFlinger* flinger,
3544 const sp<IBinder>& display,
3545 const sp<IGraphicBufferProducer>& producer,
3546 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003547 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003548 bool useIdentityTransform,
3549 Transform::orientation_flags rotation,
3550 bool isLocalScreenshot)
3551 : flinger(flinger), display(display), producer(producer),
3552 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3553 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3554 useIdentityTransform(useIdentityTransform),
3555 rotation(rotation), result(PERMISSION_DENIED),
3556 isLocalScreenshot(isLocalScreenshot)
3557 {
3558 }
3559 status_t getResult() const {
3560 return result;
3561 }
3562 virtual bool handler() {
3563 Mutex::Autolock _l(flinger->mStateLock);
3564 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3565 result = flinger->captureScreenImplLocked(hw, producer,
3566 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3567 useIdentityTransform, rotation, isLocalScreenshot);
3568 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3569 return true;
3570 }
3571 };
3572
3573 // this creates a "fake" BBinder which will serve as a "fake" remote
3574 // binder to receive the marshaled calls and forward them to the
3575 // real remote (a BpGraphicBufferProducer)
3576 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3577
3578 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3579 // which does the marshaling work forwards to our "fake remote" above.
3580 sp<MessageBase> msg = new MessageCaptureScreen(this,
3581 display, IGraphicBufferProducer::asInterface( wrapper ),
3582 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3583 useIdentityTransform, rotationFlags, isLocalScreenshot);
3584
3585 status_t res = postMessageAsync(msg);
3586 if (res == NO_ERROR) {
3587 res = wrapper->waitForResponse();
3588 }
3589 return res;
3590}
3591
3592
3593void SurfaceFlinger::renderScreenImplLocked(
3594 const sp<const DisplayDevice>& hw,
3595 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003596 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003597 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3598{
3599 ATRACE_CALL();
3600 RenderEngine& engine(getRenderEngine());
3601
3602 // get screen geometry
3603 const int32_t hw_w = hw->getWidth();
3604 const int32_t hw_h = hw->getHeight();
3605 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3606 static_cast<int32_t>(reqHeight) != hw_h;
3607
3608 // if a default or invalid sourceCrop is passed in, set reasonable values
3609 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3610 !sourceCrop.isValid()) {
3611 sourceCrop.setLeftTop(Point(0, 0));
3612 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3613 }
3614
3615 // ensure that sourceCrop is inside screen
3616 if (sourceCrop.left < 0) {
3617 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3618 }
3619 if (sourceCrop.right > hw_w) {
3620 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3621 }
3622 if (sourceCrop.top < 0) {
3623 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3624 }
3625 if (sourceCrop.bottom > hw_h) {
3626 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3627 }
3628
3629 // make sure to clear all GL error flags
3630 engine.checkErrors();
3631
3632 // set-up our viewport
3633 engine.setViewportAndProjection(
3634 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3635 engine.disableTexturing();
3636
3637 // redraw the screen entirely...
3638 engine.clearWithColor(0, 0, 0, 1);
3639
Robert Carr1f0a16a2016-10-24 16:27:39 -07003640 // We loop through the first level of layers without traversing,
3641 // as we need to interpret min/max layer Z in the top level Z space.
3642 for (const auto& layer : mDrawingState.layersSortedByZ) {
3643 if (layer->getLayerStack() != hw->getLayerStack()) {
3644 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003645 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003646 const Layer::State& state(layer->getDrawingState());
3647 if (state.z < minLayerZ || state.z > maxLayerZ) {
3648 continue;
3649 }
3650 layer->traverseInZOrder([&](Layer* layer) {
3651 if (!layer->isVisible()) {
3652 return;
3653 }
3654 if (filtering) layer->setFiltering(true);
3655 layer->draw(hw, useIdentityTransform);
3656 if (filtering) layer->setFiltering(false);
3657 });
3658 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003659
3660 // compositionComplete is needed for older driver
3661 hw->compositionComplete();
3662 hw->setViewportAndProjection();
3663}
3664
3665
3666status_t SurfaceFlinger::captureScreenImplLocked(
3667 const sp<const DisplayDevice>& hw,
3668 const sp<IGraphicBufferProducer>& producer,
3669 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003670 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003671 bool useIdentityTransform, Transform::orientation_flags rotation,
3672 bool isLocalScreenshot)
3673{
3674 ATRACE_CALL();
3675
3676 // get screen geometry
3677 uint32_t hw_w = hw->getWidth();
3678 uint32_t hw_h = hw->getHeight();
3679
3680 if (rotation & Transform::ROT_90) {
3681 std::swap(hw_w, hw_h);
3682 }
3683
3684 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3685 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3686 reqWidth, reqHeight, hw_w, hw_h);
3687 return BAD_VALUE;
3688 }
3689
3690 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3691 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3692
3693 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003694 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003695 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003696 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3697 (state.z < minLayerZ || state.z > maxLayerZ)) {
3698 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003699 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003700 layer->traverseInZOrder([&](Layer *layer) {
3701 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3702 layer->isSecure());
3703 });
3704 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003705
3706 if (!isLocalScreenshot && secureLayerIsVisible) {
3707 ALOGW("FB is protected: PERMISSION_DENIED");
3708 return PERMISSION_DENIED;
3709 }
3710
3711 // create a surface (because we're a producer, and we need to
3712 // dequeue/queue a buffer)
3713 sp<Surface> sur = new Surface(producer, false);
3714 ANativeWindow* window = sur.get();
3715
3716 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3717 if (result == NO_ERROR) {
3718 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3719 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3720
3721 int err = 0;
3722 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3723 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3724 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3725 err |= native_window_set_usage(window, usage);
3726
3727 if (err == NO_ERROR) {
3728 ANativeWindowBuffer* buffer;
3729 /* TODO: Once we have the sync framework everywhere this can use
3730 * server-side waits on the fence that dequeueBuffer returns.
3731 */
3732 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3733 if (result == NO_ERROR) {
3734 int syncFd = -1;
3735 // create an EGLImage from the buffer so we can later
3736 // turn it into a texture
3737 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3738 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3739 if (image != EGL_NO_IMAGE_KHR) {
3740 // this binds the given EGLImage as a framebuffer for the
3741 // duration of this scope.
3742 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3743 if (imageBond.getStatus() == NO_ERROR) {
3744 // this will in fact render into our dequeued buffer
3745 // via an FBO, which means we didn't have to create
3746 // an EGLSurface and therefore we're not
3747 // dependent on the context's EGLConfig.
3748 renderScreenImplLocked(
3749 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3750 useIdentityTransform, rotation);
3751
3752 // Attempt to create a sync khr object that can produce a sync point. If that
3753 // isn't available, create a non-dupable sync object in the fallback path and
3754 // wait on it directly.
3755 EGLSyncKHR sync;
3756 if (!DEBUG_SCREENSHOTS) {
3757 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3758 // native fence fd will not be populated until flush() is done.
3759 getRenderEngine().flush();
3760 } else {
3761 sync = EGL_NO_SYNC_KHR;
3762 }
3763 if (sync != EGL_NO_SYNC_KHR) {
3764 // get the sync fd
3765 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3766 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3767 ALOGW("captureScreen: failed to dup sync khr object");
3768 syncFd = -1;
3769 }
3770 eglDestroySyncKHR(mEGLDisplay, sync);
3771 } else {
3772 // fallback path
3773 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3774 if (sync != EGL_NO_SYNC_KHR) {
3775 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3776 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3777 EGLint eglErr = eglGetError();
3778 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3779 ALOGW("captureScreen: fence wait timed out");
3780 } else {
3781 ALOGW_IF(eglErr != EGL_SUCCESS,
3782 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3783 }
3784 eglDestroySyncKHR(mEGLDisplay, sync);
3785 } else {
3786 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3787 }
3788 }
3789 if (DEBUG_SCREENSHOTS) {
3790 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3791 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3792 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3793 hw, minLayerZ, maxLayerZ);
3794 delete [] pixels;
3795 }
3796
3797 } else {
3798 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3799 result = INVALID_OPERATION;
3800 window->cancelBuffer(window, buffer, syncFd);
3801 buffer = NULL;
3802 }
3803 // destroy our image
3804 eglDestroyImageKHR(mEGLDisplay, image);
3805 } else {
3806 result = BAD_VALUE;
3807 }
3808 if (buffer) {
3809 // queueBuffer takes ownership of syncFd
3810 result = window->queueBuffer(window, buffer, syncFd);
3811 }
3812 }
3813 } else {
3814 result = BAD_VALUE;
3815 }
3816 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3817 }
3818
3819 return result;
3820}
3821
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003822void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003823 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003824 if (DEBUG_SCREENSHOTS) {
3825 for (size_t y=0 ; y<h ; y++) {
3826 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3827 for (size_t x=0 ; x<w ; x++) {
3828 if (p[x] != 0xFF000000) return;
3829 }
3830 }
3831 ALOGE("*** we just took a black screenshot ***\n"
3832 "requested minz=%d, maxz=%d, layerStack=%d",
3833 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003834 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003835 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003836 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003837 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3838 state.z <= maxLayerZ) {
3839 layer->traverseInZOrder([&](Layer* layer) {
3840 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3841 layer->isVisible() ? '+' : '-',
3842 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003843 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003844 i++;
3845 });
3846 }
3847 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003848 }
3849}
3850
3851// ---------------------------------------------------------------------------
3852
Robert Carr2047fae2016-11-28 14:09:09 -08003853void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3854 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003855}
3856
Robert Carr2047fae2016-11-28 14:09:09 -08003857void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3858 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003859}
3860
3861}; // namespace android
3862
3863
3864#if defined(__gl_h_)
3865#error "don't include gl/gl.h in this file"
3866#endif
3867
3868#if defined(__gl2_h_)
3869#error "don't include gl2/gl2.h in this file"
3870#endif