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