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