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