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