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